SQL Sum Query问题

时间:2016-06-28 19:31:38

标签: sql-server sum

我是SQL Server的新手并且正在努力解决这个问题。

我有两个选择语句

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

我希望输出显示为两列

SQL Server屏幕上的

(第1列+星期一)和(第2列=星期二)

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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)

请记住,这是伪代码,我正在查找“dayofweek”属性......

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

答案 2 :(得分:0)

我认为您需要使用MSSQL Pivot函数将行转换为列。 检查另一个问题。也许这可以帮助你: Convert Rows to columns using 'Pivot' in SQL Server