我有这些当前的结果
PersonName Team Daily Amount Date
Alex 4 10 2017-01-11
Alex 4 10 2017-01-11
Alex 4 10 2017-01-11
Ben 1 10 2017-02-11
Ben 1 10 2017-02-11
Ben 1 10 2017-01-11
Fred 3 10 2017-01-11
Fred 3 10 2017-01-11
Fred 3 10 2017-01-11
Sam 2 10 2017-02-11
Sam 2 10 2017-01-11
Sam 2 10 2017-01-11
Tom 2 10 2017-01-11
Tom 2 10 2017-02-11
Tom 2 10 2017-01-11
现在,我希望在两个单独的栏目中创建每日和每月的数字。
我正在寻找这样的结果:
PersonName Team Daily Amount Date Monthly Figure
Alex 4 30 2017-01-11 30
Ben 1 10 2017-01-11 30
Fred 3 10 2017-01-11 30
Sam 2 20 2017-01-11 30
Tom 2 20 2017-01-11 30
到目前为止,我有这样的查询,但我不确定这是最好的方法。它给了我不同的分组总和结果比我预期的。
SELECT P.PersonName, min(P.Team) AS [Team],
SUM(F.Amount) AS [Daily Amount], min(F.Date) AS [Date], MTD.[Month To Date]
FROM Person P
JOIN Figure F on P.PersonID =F.PersonFK
WHERE DATEDIFF( d, F.Date, GETDATE() ) = 1
GROUP BY P.PersonName
JOIN
(SELECT
P.PersonName, min(P.Team) AS [Team],
SUM(F.Amount) AS [Month To Date]
, min(F.Date) AS [Date]
FROM Person P
JOIN Figure F on P.PersonID =F.PersonFK
F.Date BETWEEN CAST(MONTH(GETDATE())
AS VARCHAR) + '/' + '01/' + + CAST(YEAR(GETDATE()) AS VARCHAR)
AND GETDATE()
GROUP BY P.PersonName ) MTD
ON MTD.PersonName = P.PersonName
我已尝试过连接子查询以及使用联合但我无法得到我想要的结果。任何人都可以进一步建议我吗?感谢
SQL FIDDLE - http://sqlfiddle.com/#!6/23bbb/12
答案 0 :(得分:1)
如果我理解正确,您希望找到每个人在特定日期支出的金额,并将其与该月的金额进行比较
declare @day date = '01-11-17'
select P.PersonName,
P.Team AS [Team],
sum(case when date = @day then f.amount end) AS [daily amount] ,
@day AS [Date],
sum(F.Amount) AS [monthly amount]
from Person P
join Figure F on P.PersonID =F.PersonFK
where month(F.date) = month(@day)
group by P.PersonName, P.Team