按日SQL Server汇总每周订单数据

时间:2017-07-14 16:15:29

标签: sql sql-server count group-by distinct

我有一个包含以下数据的表:

Item       Date      Customer
------------------------------
apple   01/01/2017      a
apple   01/01/2017      a
apple   02/01/2017      b
apple   05/01/2017      c
apple   06/01/2017      b
apple   06/01/2017      d
apple   07/01/2017      c
apple   09/01/2017      a
banana  01/01/2017      b
banana  02/01/2017      a

我需要的是按日分组的摘要,以及当天(即白天+3天)以及当天本周WEEK中有多少UNIQUE客户购买该项目的项目。

它应该是这样的:

Item         Date       Weekly Customers   Daily Customers
-----------------------------------------------------------
    apple   01/01/2017         2               1
    apple   02/01/2017         3               1
    apple   05/01/2017         3               1
    apple   06/01/2017         4               2
    apple   07/01/2017         4               1
    apple   09/01/2017         4               1
    banana  01/01/2017         2               1
    banana  02/01/2017         2               1

我设法按项目,日期,独特的每日客户进行总结,我认为这是正确的:

SELECT 
    item as 'Item', boughtDate as 'Date',
    COUNT(DISTINCT(customer)) as 'Daily Customers'
FROM tbl1 
GROUP BY Item, Date

我真的很难理解如何将每个不同的项目+天组合,并获得当天所在星期(当天任何一天的3天)的总独特客户,并加入这些结果。< / p>

我一直在玩一些循环和CTE,但我似乎遇到的问题是在任何给定的字段中没有任何值是唯一的。我确信有一种简单的方法可以做到这一点,我只是没想到?

2 个答案:

答案 0 :(得分:0)

除了参数化查询外,这还​​能满足您的需求吗?

将日期更改为表示结果所代表日期的字符串?由于在此示例中字符串是固定的,因此应用max()不会将其作为group by子句的一部分。

SELECT 
      item as 'Item', 
      max( 'Week of 7-11 to 7-17' ) as 'Date',
      COUNT(DISTINCT(customer)) as 'Weekly Customers'
   FROM 
      tbl1
   where 
          boughtDate >= '2017-07-11' 
      and boughtDate < '2017-07-18'
   GROUP BY 
      Item

... OR 如果一个人进来并且每2-3天购买一次,那么如果你在购买的时间+/- 3天内寻找每个人,这可能是一个连续的滚动时间段。

答案 1 :(得分:0)

SELECT item as 'Item', max( 'Week of 7-11 to 7-17' ) as 'Date', COUNT(DISTINCT(customer)) as 'Weekly Customers' FROM tbl1 where boughtDate >= '2017-07-11' and boughtDate < '2017-07-18' GROUP BY Item

我会尝试这样的事情。

相关问题