I would like to have a query that uses the greater of two values/columns if a certain other value for the record is true.
I'm trying to get a report account holdings. Unfortunately the DB usually stores the value of Cash in a column called HoldingQty
, while for every other type of holding (stocks, bonds, mutual funds) it stores it in a column called Qty
.
The problem is that sometimes the value of the cash is stored in Qty
only, and sometimes it is in both Qty
and HoldingQty
. Obviously sometimes it is stored only in HoldingQty
as mentioned above.
Basically I want my select statement to say "if the security is cash, look at both qty and holding qty and give me the value of whatever is greater. Otherwise, if the security isn't cash just give me qty".
How would I write that in T-SQL? Here is my effort:
SELECT
h.account_name, h.security_name, h.security_type, h.price,
(CASE:
WHEN security_type = 'cash'
THEN (WHEN h.qty > h.holdingqty
THEN h.qty
ELSE h.holdingqty)
ELSE qty) as quantity,
h.total_value
FROM
holdings h
WHERE
...........
In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.
Here's the generic SQL query to two compare columns (column1, column2) in a table (table1). mysql> select * from table1 where column1 not in (select column2 from table1); In the above query, update table1, column1 and column2 as per your requirement.
Navigate to the "Home" option and select duplicate values in the toolbar. Next, navigate to Conditional Formatting in Excel Option. A new window will appear on the screen with options to select "Duplicate" and "Unique" values. You can compare the two columns with matching values or unique values.
Comparison of columns in the same table is possible with the help of joins. Here we are comparing all the customers that are in the same city using the self join in SQL. Self-join is a regular join where a table is joined by itself. Similarly, a table may be joined with left join, right join, inner join, and full join.
Your query is correct but need few syntax arrangement, try below code
SELECT h.account_name, h.security_name, h.security_type, h.price,
CASE WHEN security_type = 'cash' then
CASE when h.qty > h.holdingqty then h.qty
else h.holdingqty END
ELSE qty END AS 'YourColumnName'
) as quantity, h.total_value
FROM holdings h
where ...........
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With