在MSSQL中使用两个表:
一张表,[CUSTOMER],包含有关捐助者的信息。 - 相关列:[CustID],[Name] 一张桌子,[捐赠],包含每次捐赠的记录。 - 相关列:[CustID],[Amount],[Date] 这些表共享一个密钥[CustID]。
我想根据每个[CustID]
汇总[Amounts]SELECT DONATION.CUSTID
,PEOPLE.NAME
,SUM (DONATION.AMOUNT) as TOTAL_DONATION
FROM [dbo].[DONATION] INNER JOIN [dbo].[PEOPLE] ON DONATION.CUSTID = PEOPLE.CUSTID
GROUP BY
DONATION.CUSTID
,PEOPLE.NAME
HAVING SUM (DONATION.AMOUNT) > 100
此查询正常,即使添加了HAVING子句也是如此。
当我想限制捐款的日期汇总时(加入SELECT,GROUP BY和HAVING条款)但是......
SELECT DONATION.CUSTID
,PEOPLE.NAME,DONATION.DATE
,SUM (DONATION.AMOUNT) as TOTAL_DONATION
FROM [dbo].[DONATION] INNER JOIN [dbo].[PEOPLE] ON DONATION.CUSTID = PEOPLE.CUSTID
GROUP BY
DONATION.CUSTID
,PEOPLE.NAME
,DONATION.DATE
HAVING SUM (DONATION.AMOUNT) > 100
and DONATION.DATE > '1-1-2010'
查询不再返回每个人捐款的总和,但会返回符合HAVING标准的每个人的个人捐款。
如何实施此日期限制?是我加入或总结或......?感谢。
答案 0 :(得分:5)
将其移至 WHERE 子句
SELECT DONATION.CUSTID
,PEOPLE.NAME
,SUM (DONATION.AMOUNT) as TOTAL_DONATION
FROM [dbo].[DONATION]
INNER JOIN [dbo].[PEOPLE] ON DONATION.CUSTID = PEOPLE.CUSTID
WHERE DONATION.DATE > '1-1-2010'
GROUP BY
DONATION.CUSTID
,PEOPLE.NAME
HAVING SUM (DONATION.AMOUNT) > 100
这意味着什么:
- given the people who donated
- look only at data where donation date is in 2010 or later
- and within that data, show the people who donated a total of more than 100
答案 1 :(得分:0)
修改您的第一个查询,如:
,SUM (CASE WHEN DONATION.DATE > '1-1-2010' THEN DONATION.AMOUNT END)
as TOTAL_DONATION
答案 2 :(得分:0)
除非您希望每个客户每个日期有一行,否则您无法按日期分组。 如何从捐赠表中查找并查找客户名称?
选择捐赠者=(从[人]中选择名称,其中[人物] .custid = [捐赠] .custid), 客户ID,SUM(量) 来自[捐款] 哪里[捐款]。日期'1/1/2011'和'1/15/2011' custid小组 SUM(量)> 100