作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一张像这样“预订”的 table :
booking_id,
date,
client,
sponsor
SELECT
MONTH(date) AS M,
Sponsor,
Client,
COUNT(booking_id) AS c
FROM booking
GROUP BY
M, Sponsor, Client
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
最佳答案
SELECT [Month] = DATENAME(MONTH, M), Sponsor, Client, c,
[dates] = STUFF((SELECT ', ' + 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('')), 1, 2, '')
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('')), 1, 2, '')
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
关于sql-server - 模仿 group_concat() 结合 GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10298805/
我是一名优秀的程序员,十分优秀!