如何使用最大功能计数和分组依据

时间:2018-08-23 17:02:00

标签: sql sql-server tsql

我在下面使用此查询来获取陈旧帐户的列表,但我想尝试获取返回的行数(而不是完整的列表),但卡住了并寻求帮助。

SELECT customer_name, MAX(order_date) AS last_Sale_Date
FROM sales_history
GROUP BY customer_name
HAVING max(order_date) <= '01/01/2017 23:59:59'

3 个答案:

答案 0 :(得分:1)

您可以使用:

SELECT TOP 1 COUNT(*) OVER()
FROM sales_history
GROUP BY customer_name
HAVING max(order_date) <='01/01/2017 23:59:59';

DBFiddle Demo

答案 1 :(得分:0)

使用子查询:

SELECT COUNT(*)
FROM (SELECT customer_name, MAX(order_date) AS last_Sale_Date
      FROM sales_history
      GROUP BY customer_name
      HAVING max(order_date) < '2018-01-02'
     ) sh

请注意,我在HAVING子句中更改了日期格式。

答案 2 :(得分:0)

我将把它放在另一处,可能是我写的方式:

select count(*)
from (select customer_name, max(order_Date) LastOrder
      from sales_history
      group by customer_name) LastOrders --Everyones last order
where LastOrder < '2018-01-02'

导致自2018年1月2日以来未订购的客户数量。