在SQL中计算总和并将其显示为另一列?

时间:2014-05-31 20:31:48

标签: sql sql-server

我使用以下查询来计算客户的信用,但问题是我想计算另一个中的CREDIT列的总和,它只是总结CREDIT并显示在另一列中。是否有任何方法可以做到这一点通过修改以下查询? 任何帮助都会非常值得赞赏。

Select
    CUSTOMER_NAME
   ,TODAYS_TOTAL
   ,AMOUNT_RECIEVED
   ,DATE_SALE
   ,ITEM_MODEL
   ,QUANTITY
   ,CREDIT = (CASE 
      WHEN AMOUNT_RECIEVED=0 AND TODAYS_TOTAL>0 AND CREDIT =0 THEN TODAYS_TOTAL 
      WHEN AMOUNT_RECIEVED>0 AND TODAYS_TOTAL>0 AND CREDIT>=0 THEN (CREDIT+TODAYS_TOTAL)-AMOUNT_RECIEVED
      WHEN AMOUNT_RECIEVED>0 AND TODAYS_TOTAL=0 AND CREDIT >0 THEN (CREDIT-AMOUNT_RECIEVED)
      END) 
From CUSTOMER_CREDIT_RECORDS 
WHERE CUSTOMER_NAME='Saad NED'

1 个答案:

答案 0 :(得分:2)

首先,这是您的查询更易于理解的格式:

Select CUSTOMER_NAME, TODAYS_TOTAL, AMOUNT_RECIEVED, DATE_SALE, ITEM_MODEL, QUANTITY,
       CREDIT = (CASE WHEN AMOUNT_RECIEVED=0 AND TODAYS_TOTAL>0 AND CREDIT=0
                      THEN TODAYS_TOTAL 
                      WHEN AMOUNT_RECIEVED>0 AND TODAYS_TOTAL>0 AND CREDIT>=0
                      THEN (CREDIT+TODAYS_TOTAL)-AMOUNT_RECIEVED
                      WHEN AMOUNT_RECIEVED>0 AND TODAYS_TOTAL=0 AND CREDIT>0
                      THEN (CREDIT-AMOUNT_RECIEVED)
                 END) 
From CUSTOMER_CREDIT_RECORDS
WHERE CUSTOMER_NAME = 'Saad NED';

您只有一位客户,因此大多数列对于每日总计没有意义。你可以这样做:

Select CUSTOMER_NAME, 
       SUM(CASE WHEN AMOUNT_RECIEVED=0 AND TODAYS_TOTAL>0 AND CREDIT=0
                THEN TODAYS_TOTAL 
                WHEN AMOUNT_RECIEVED>0 AND TODAYS_TOTAL>0 AND CREDIT>=0
                THEN (CREDIT+TODAYS_TOTAL)-AMOUNT_RECIEVED
                WHEN AMOUNT_RECIEVED>0 AND TODAYS_TOTAL=0 AND CREDIT>0
                THEN (CREDIT-AMOUNT_RECIEVED)
           END) as CREDIT
From CUSTOMER_CREDIT_RECORDS
WHERE CUSTOMER_NAME = 'Saad NED'
GROUP BY CUSTOMER_NAME;

但是,我对case语句中的算术感到好奇。您是否厌恶添加0的值?这似乎更简单:

Select CUSTOMER_NAME, 
       SUM(CREDIT + TODAYS_TOTAL - AMOUNT_RECIEVED) as CREDIT
From CUSTOMER_CREDIT_RECORDS
WHERE CUSTOMER_NAME = 'Saad NED'
GROUP BY CUSTOMER_NAME;

这假定至少满足一个when条件。