TSQL:按周对客户订单进行分组

时间:2010-03-11 23:30:49

标签: sql-server tsql

我有一张包含订单集合的表格。字段是:

  • customerName(文字)
  • DateOfOrder(日期时间)。

我想显示每位客户每周的订单总数。我想安排在每周的星期五这样看起来像这样:

all dates follow mm/dd/yyyy

"bobs pizza", 3/5/2010, 10
"the phone co",3/5/2010,5
"bobs pizza", 3/12/2010, 3
"the phone co",3/12/2010,11

有人可以告诉我该怎么做吗?

由于

5 个答案:

答案 0 :(得分:15)

制作一个可以更容易分组的字段。

SELECT COUNT(OrderID), WeekStart
FROM 
(
 SELECT *, 
  dateadd(week, datediff(day,'20000107',yourDate) / 7, '20000107') AS WeekStart  
 FROM Orders
) o
GROUP BY WeekStart;

20000107是一个众所周知的星期五。

答案 1 :(得分:2)

这不是一个完整的订单,但它会给你一周#。只需要添加分组。

SELECT
Cast(DatePart(YEAR, dateadd(month, datediff(month, 0, DateOfOrder),0))
    AS nvarchar(20))
 + ' '
 + RIGHT('0' + Cast(DatePart(WK, DateOfOrder) AS nvarchar(20)), 2)
,CustomerName
FROM Orders

答案 2 :(得分:2)

试着试一试

DECLARE @Table TABLE(
        customerName VARCHAR(50),
        DateOfOrder DATETIME,
        Quantity FLOAT
        )

INSERT INTO @Table SELECT 'bobs pizza', '1/5/2010', 10      
INSERT INTO @Table SELECT 'bobs pizza', '3/5/2010', 10 
INSERT INTO @Table SELECT 'bobs pizza', '3/4/2010', 10 
INSERT INTO @Table SELECT 'the phone co','3/5/2010',5 
INSERT INTO @Table SELECT 'bobs pizza', '3/12/2010', 3 
INSERT INTO @Table SELECT 'the phone co','3/12/2010',11 
INSERT INTO @Table SELECT 'the phone co','3/13/2010',11 
INSERT INTO @Table SELECT 'the phone co','3/15/2010',11 


SELECT  DateFirday,
        DATENAME(dw, DateFirday),
        SUM(Quantity) Total
FROM    (
            SELECT  *,
                    DATEADD(week, DATEPART(WEEK, DateOfOrder) - 1, CAST('01 Jan' + CAST(DATEPART(year,DateOfOrder) AS VARCHAR(4)) AS DATETIME)) DateFirday
            FROM    @Table
        ) sub
GROUP BY DateFirday

输出

DateFirday                                             Total
----------------------- ------------------------------ ----------------------
2010-01-08 00:00:00.000 Friday                         10
2010-03-05 00:00:00.000 Friday                         25
2010-03-12 00:00:00.000 Friday                         25
2010-03-19 00:00:00.000 Friday                         11

如果我错过了星期五的日期,请告诉我,我可以看看。

答案 3 :(得分:2)

我想我会加上这个,因为我不喜欢现有的最佳答案。它只是减去工作日,然后再加回到所需的日期。如果你想要一周中不同的一天(或者你的DATEFIRST设置与我收集的不同,请调整6)。

SELECT Friday, COUNT(CustomerName)
FROM 
(
 SELECT *, 
  CAST(DATEADD(d, 6 - DATEPART(dw,DateOfOrder), DateOfOrder) AS date) AS Friday  
 FROM Orders
) o
GROUP BY Friday;

答案 4 :(得分:1)

只要没有时间组件,这将有效:

SELECT     DateOfOrder - DATEPART(dw, DateOfOrder) + 7 AS weekEndingDate, customerName, COUNT(*) AS totalOrders
FROM         Orders
GROUP BY DateOfOrder - DATEPART(dw, DateOfOrder) + 7, customerName

这假定DATEFIRST尚未更改。减法将回到星期六,然后+ 7到星期五。

如果有时间组件,请使用其中一种标准技术将其剥离:

DATEADD(day, DATEDIFF(day, 0, DateOfOrder), 0) - DATEPART(dw, DateOfOrder) + 7

CAST(FLOOR(CAST(DateOfOrder as FLOAT)) as DATETIME) - DATEPART(dw, DateOfOrder) + 7

或,对于SS2008

CAST(DateOfOrder AS date) - DATEPART(dw, DateOfOrder) + 7