每天总金额

时间:2019-09-14 12:57:57

标签: sql sql-server tsql aggregate

下面是两个示例查询,如何将它们组合起来以按天计算总数?

因此,预期结果例如:

2019年8月9日-$ 500

2019年8月8日-$ 400

select sum(Amount)
from 
(
select sum(Amount) as Amount from FactFinance FA
Inner Join DimDate DD on 
FA.DateKey = DD.DateKey
where DD.Date <= '09 Aug 2019'
group by OccKey
having sum(Amount) >0
) a

select sum(Amount)
from 
(
select sum(Amount) as Amount from FactFinance FA
Inner Join DimDate DD on 
FA.DateKey = DD.DateKey
where DD.Date <= '08 Aug 2019'
group by OccKey
having sum(Amount) >0
) a

3 个答案:

答案 0 :(得分:0)

您可以通过子选择使用以下解决方案来获取SUM

SELECT DD.Date, (
  SELECT SUM(Amount) 
  FROM FactFinance 
    INNER JOIN DimDate ON FactFinance.DateKey = DimDate.DateKey
  WHERE DimDate.[Date] <= DD.[Date]
) AS Amount 
FROM FactFinance FA 
  INNER JOIN DimDate DD ON FA.DateKey = DD.DateKey
WHERE DD.Date <= '09 Aug 2019' -- your max date to show in result
GROUP BY DD.Date

使用SUM (...) OVER (...)的另一种解决方案:

SELECT DD.[Date], SUM(SUM(Amount)) OVER (ORDER BY DD.[Date]) AS Amount
FROM FactFinance FA INNER JOIN DimDate DD ON FA.DateKey = DD.DateKey
WHERE DD.[Date] <= '09 Aug 2019' -- your max date to show in result
GROUP BY DD.[Date]

您可以将上面的查询放入子选择中,以排除数量为0或更低的行:

SELECT * FROM (
  SELECT DD.[Date], SUM(SUM(Amount)) OVER (ORDER BY DD.[Date]) AS Amount
  FROM FactFinance FA INNER JOIN DimDate DD ON FA.DateKey = DD.DateKey
  WHERE DD.[Date] <= '09 Aug 2019' -- your max date to show in result
  GROUP BY DD.[Date]
) tSumAmount
WHERE tSumAmount.Amount > 0

答案 1 :(得分:0)

您可以做类似的事情

select CONVERT(date, DD.Date) as Date, sum(Amount) as Amount from FactFinance FA
Inner Join DimDate DD on 
FA.DateKey = DD.DateKey
where DD.Date in('09 Aug 2019', '08 Aug 2019')
group by CONVERT(date, DD.Date)
having sum(Amount) >0

答案 2 :(得分:0)

UNDERLAY