2

我有一张这样的“预订”表:

booking_id,
date,
client,
sponsor

我正在尝试获取每月摘要:

SELECT 
  MONTH(date) AS M,
  Sponsor,
  Client,
  COUNT(booking_id) AS c
FROM booking
GROUP BY
 M, Sponsor, Client

现在我想看看客户在哪个日期进行了预订。我尝试使用 STUFF() (在这篇文章中引用:在 Microsoft SQL Server 2005 中模拟 group_concat MySQL 函数?),但它与 group-by 语句冲突。

根据要求采样数据。目前我有以下内容:

M       Sponsor     Client  c     
March   AB          y       3
March   FE          x       4
April   AB          x       2

期望的输出:

M       Sponsor     Client  c   dates
March   AB          y       3   12, 15, 18
March   FE          x       4   16, 19, 20, 21
April   AB          x       2   4, 8

其中数字是天数(例如 3 月 12 日、3 月 15 日、3 月 18 日)。在 mysql 中,我会使用 group_concat(date) 来获取最后一列。

非常感谢答案:-)

4

1 回答 1

3
SELECT [Month] = DATENAME(MONTH, M), Sponsor, Client, c,
  [dates] = STUFF((SELECT N', ' + RTRIM(DATEPART(DAY, [date])) 
    FROM dbo.booking AS b
    WHERE b.Sponsor = x.Sponsor
      AND b.Client = x.Client
      AND b.[date] >= x.M AND b.[date] < DATEADD(MONTH, 1, x.M) 
    ORDER BY [date]
    FOR XML PATH(''),
    TYPE).value(N'./text()[1]', N'nvarchar(max)'), 1, 2, N'')
FROM 
(
  SELECT 
      M = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', [date]), '19000101'),
      Sponsor,
      Client,
      COUNT(booking_id) AS c
    FROM dbo.booking
    GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, '19000101', [date]), '19000101'),
      Sponsor,
      Client
) AS x
ORDER BY M, Sponsor, Client;

请注意,如果赞助商/客户组合在同一天有两个预订,则日期编号将出现在列表中两次。

编辑这是我的测试方式:

DECLARE @booking TABLE
( 
  booking_id INT IDENTITY(1,1) PRIMARY KEY,
  [date] DATE,
  Sponsor VARCHAR(32),
  Client VARCHAR(32)
);

INSERT @booking([date], Sponsor, Client) VALUES
('20120312','AB','y'), ('20120315','AB','y'), ('20120318','AB','y'),
('20120316','FE','x'), ('20120319','FE','x'), ('20120321','FE','x'), 
('20120320','FE','x'), ('20120404','AB','x'), ('20120408','AB','x');

SELECT [Month] = DATENAME(MONTH, M), Sponsor, Client, c,
  [dates] = STUFF((SELECT ', ' + RTRIM(DATEPART(DAY, [date])) 
    FROM @booking AS b
    WHERE b.Sponsor = x.Sponsor
      AND b.Client = x.Client
      AND b.[date] >= x.M AND b.[date] < DATEADD(MONTH, 1, x.M) 
    ORDER BY [date]
    FOR XML PATH(''),
    TYPE).value(N'./text()[1]', N'nvarchar(max)'), 1, 2, N'')
FROM 
(
  SELECT 
      M = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', [date]), '19000101'),
      Sponsor,
      Client,
      COUNT(booking_id) AS c
    FROM @booking
    GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, '19000101', [date]), '19000101'), 
      Sponsor, 
      Client
) AS x
ORDER BY M, Sponsor, Client;

结果:

Month   Sponsor Client  c       dates
------- ------- ------- ------- --------------
March   AB      y       3       12, 15, 18
March   FE      x       4       16, 19, 20, 21
April   AB      x       2       4, 8
于 2012-04-24T14:15:24.090 回答