如何在2个不同的查询中返回每个分组日期的总和

时间:2016-06-08 06:26:08

标签: sql sql-server-2008

每个分组日期必须根据行总和返回不同的值,我的查询返回Subquery返回的值超过1的错误,这不是我期望的返回值,干杯!

Select 
(select 
SUM(Amount) from [The Cravings Group 2013$G_L Entry]
where [G_L Account No_] in ('5010', '5011','5020','5030')
and [Global Dimension 1 Code] = 'FNB CFSI CRA KAT'
and [Posting Date] between '2016-01-08 00:00:00.000' and '2016-01-09 00:00:00.000' group by [Posting Date])
+
(select Sum(Amount)from [The Cravings Group 2013$G_L Entry]
where [G_L Account No_] between '5041' and '5047'
and [Global Dimension 1 Code] = 'FNB CFSI CRA KAT'
and [Posting Date] between '2016-01-08 00:00:00.000' and '2016-01-09 00:00:00.000' group by [Posting Date]),
[Posting Date]
from [The Cravings Group 2013$G_L Entry] 
where [Posting Date] between '2016-01-08 00:00:00.000' and '2016-01-09 00:00:00.000'
Group by [Posting Date];

1 个答案:

答案 0 :(得分:0)

您的子查询与主查询无关,并且它们输出多行结果,因此您无法将表插入行中。使用CASE尝试此查询。

Select 

SUM(
      CASE WHEN [G_L Account No_] in ('5010', '5011','5020','5030')
                and [Global Dimension 1 Code] = 'FNB CFSI CRA KAT'
                THEN Amount
                ELSE 0
      END 

    )
  +
SUM(
      CASE WHEN [G_L Account No_] between '5041' and '5047'
                and [Global Dimension 1 Code] = 'FNB CFSI CRA KAT'
                THEN Amount
                ELSE 0
      END 

    ) As SumOfAmounts
,
[Posting Date]
from [The Cravings Group 2013$G_L Entry] 
where [Posting Date] between '2016-01-08 00:00:00.000' and '2016-01-09 00:00:00.000'
Group by [Posting Date];