【问题标题】:Group by having for month按月分组
【发布时间】:2016-09-07 10:44:49
【问题描述】:

如果我需要在 2014 年 1 月 1 日至 2015 年 12 月 31 日期间每月至少购买一次且总和大于 100 点的 SQL 产品名称中显示,这是正确的方法?

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

【问题讨论】:

  • 这是否给出了正确的结果?
  • 常规 GROUP BY 提示。在选择列表中具有相同的列(设置函数的参数除外),如 group by 子句。

标签: sql sql-server group-by


【解决方案1】:

您的查询很接近,但不太正确。问题是 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;

注意事项:

  • 使用表别名时,表名的缩写比任意字母更容易理解。
  • 通常,您希望包括支出发生的月份。
  • 与您的查询不同的是group by 子句中的year()

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      相关资源
      最近更新 更多