如果我需要显示SQL产品名称,这些产品名称在一个月内至少购买一次,且在2014-01-01至2015-12-31期间的那个月总金额超过100分,这是否正确接近?
select b.ProductName, Sum(a.RequestedAmount) as summ
from ProductRequest a
join product b on a.productid=b.productid
where a.AppDate >= '2014-01-01' and a.AppDate <= '2015-12-31'
group by b.ProductName, month (a.appDate)
having Sum(a.RequestedAmount) > 100
答案 0 :(得分:2)
您的查询已结束但不太正确。问题是month()
会返回1到12之间的月份数。您的时间跨度超过了年份,因此您需要考虑年份:
select p.ProductName, Sum(pr.RequestedAmount) as summ
from ProductRequest pr join
Product p
on pr.productid = p.productid
where pr.AppDate >= '2014-01-01' and pr.AppDate <= '2015-12-31'
group by p.ProductName, year(pr.appDate), month(pr.appDate)
having sum(pr.RequestedAmount) > 100;
注意:
year()
子句中的group by
。答案 1 :(得分:1)
SELECT * FROM
(
SELECT b.ProductName, month (a.appDate), Sum(a.RequestedAmount) as summ
from ProductRequest a
join product b on a.productid=b.productid
where a.AppDate>='2014-01-01' and a.AppDate<='2015-12-31'
group by b.ProductName, month (a.appDate)
) x
where x.summ>100