简体   繁体   English

在With子句中使用日期列分组

[英]Group By with date column in the having clause

customer    price   date
123         100     1-Jan-15
321         200     2-Jan-15
123         10      3-Jan-15
123         50      4-Jan-15
321         150     5-Jan-15
123         100     6-Jan-15
123         300     7-Jan-15
321         500     8-Jan-15
123         700     9-Jan-15

I would like to take see SUM(Price) between dates 3-Jan and 7-Jan group by customer 我想按照客户的要求,在3月1日至7月1日期间看到SUM(价格)

Something like: 就像是:

select customer,sum(price) from table group by customer 
having date between 3-Jan-2015 and 8-Jan-2015 

This prompts me to have date either in the select or group by clause. 这提示我在selectgroup by子句中有date When I include it, it groups by Date also. 当我包含它时,它也按日期分组。

Desired output is: 期望的输出是:

123 460

The HAVING clause filters results after the grouping and aggregation, so in order to do this any fields you want in the HAVING clause must be in the GROUP BY or SELECT lists. HAVING子句在分组和聚合之后过滤结果,因此为了做到这一点, HAVING子句中所需的任何字段必须位于GROUP BYSELECT列表中。 The WHERE clause filters the rows before doing the grouping and aggregation. WHERE子句执行分组和聚合之前过滤行。

To get the results you want, simply move the date between... condition into a WHERE clause: 要获得所需的结果,只需将date between...date between...移动到WHERE子句中:

SELECT customer,SUM(price)
  FROM table
  WHERE date BETWEEN 3-Jan-2015 AND 8-Jan-2015
  GROUP BY customer 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM