Select 比较两列的情况

Select case comparing two columns

如果记录的某个其他值为真,我想要一个使用两者中较大者的查询 values/columns。

我正在尝试获取报告帐户持有量。不幸的是,数据库通常将 Cash 的值存储在名为 HoldingQty 的列中,而对于所有其他类型的持有(股票、债券、共同基金),它会将其存储在名为 Qty.[=18 的列中=]

问题是现金的价值有时只存储在 Qty 中,有时它同时存在于 QtyHoldingQty 中。显然有时它只存储在HoldingQty中,如上所述。

基本上我希望我的 select 声明说 "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"。

我如何在 T-SQL 中写它?这是我的努力:

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
    ...........

您的查询是正确的,但需要一些语法安排,请尝试以下代码

   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 ...........

快到了!

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 quantity ,
    h.total_value
FROM    holdings h
 WHERE ...........

您可以使用嵌套的 case 表达式实现此行为:

SELECT h.account_name, h.security_name, h.security_type, h.price,
       CASE security_type 
       WHEN 'cash' THEN  CASE WHEN h.qty > h.holdingqty THEN h.qty
                                                        ELSE h.holdingqty
                         END
       ELSE h.qty
       END
FROM   holdings h
WHERE  ...........