2016-06-28 133 views
2

我是SQL Server的新手,併爲此苦苦掙扎。SQL總和查詢問題

我有兩個選擇語句

SELECT 
    SUM(Amount) AS "MONDAY" 
FROM 
    Transaction 
WHERE 
    Transaction_Date = '2015-12-21 00:00:00.000' 

SELECT 
    SUM(Amount) AS "TUESDAY" 
FROM 
    Transaction 
WHERE 
    Transaction_Date = '2015-12-22 00:00:00.000' 

他們的結果是2,00,000和3,00,000分別

我想要的輸出被示爲兩列

(柱1 +週一)和(列2 =星期二)在SQL Server屏幕上

回答

6

一個選項是使用conditional aggregation爲:

SELECT SUM(CASE WHEN Transaction_Date = '2015-12-21 00:00:00.000' 
      THEN Amount END) AS "MONDAY" , 
     SUM(CASE WHEN Transaction_Date = '2015-12-22 00:00:00.000' 
      THEN Amount END) AS "TUESDAY" 
FROM Transaction 
+0

正是醫生的命令.... :)真棒 – Arav

1
select datepart(dw, transactiondate), 
    sum(amount) [sum] 
from transaction 
where transaction_date between '2015-12-22' and '2015-12-23' 
group by datepart(dayofweek, transactiondate) 

記住,這是僞代碼,我找了「星期幾」的屬性...

查找日期部分在這裏:https://msdn.microsoft.com/en-us/library/ms174420.aspx

+0

好方法,但這將創建多個結果與多列單行... – sgeddes

+0

啊是的...我的壞 – ganders