我有一个带作品集的日期列表,一个作品集可以有多个日期。作品集是员工假期请求对开页。 (SQL Server 2008)
我不需要像列表那样显示信息,而是需要以下列格式显示
这是SQL小提琴。
http://sqlfiddle.com/#!3/0ddd2/7
感谢任何指南。
答案 0 :(得分:5)
这可以使用带子查询的STUFF函数来完成。语法是:
SELECT Result2.Folio,
LEFT(Result2.Dates, LEN(Result2.Dates) -1) AS Dates,
Result2.Month,
Result2.Year,
Result2.[Total Days]
FROM
(
SELECT Result.Folio,
STUFF((SELECT ' ' + CAST(DATEPART(dd,hi2.date) AS VARCHAR) + ','
FROM employee_holiday_item hi2
WHERE hi2.holidayid = result.Folio
AND Result.Month = DATEPART(mm,hi2.date)
AND Result.Year = DATEPART(yyyy,hi2.date)
ORDER BY DATEPART(dd,hi2.date)
FOR XML PATH ('') ),1,1,'') AS 'Dates',
Result.Month,
Result.Year,
Result.[Total Days]
FROM (
SELECT hi.holidayid as Folio,
DATEPART(mm,hi.date) AS Month,
DATEPART(yyyy,hi.date) AS Year,
COUNT(*) AS 'Total Days'
FROM employee_holiday_item hi
GROUP BY hi.holidayid, DATEPART(mm,hi.date), DATEPART(yyyy,hi.date)
) AS Result
) AS Result2
答案 1 :(得分:4)
拉里的答案基本上是正确的(我正在推荐它)。但它有一些缺点:
varchar()
没有长度。stuff()
。字符串连接实际上由for xml path
完成,而不是由stuff()
完成。 stuff()
只删除前导逗号。
更好的配方可以省去不必要的子查询。另外,我强烈建议在datepart()
中使用日期部分名称。谁想要记住mm
是指分钟还是几个月,何时可以分别使用“分钟”和“月份”?
SELECT hi.holidayid as Folio,
STUFF((SELECT ',' + CAST(DATEPART(day, hi2.date) AS VARCHAR(255))
FROM employee_holiday_item hi2
WHERE hi2.holidayid = hi.holidayid AND
DATEPART(month, hi.date) = DATEPART(month, hi2.date) AND
DATEPART(year, hi.date) = DATEPART(year,hi2.date)
ORDER BY DATEPART(dd,hi2.date)
FOR XML PATH ('')
), 1, 1, '') as dates,
DATEPART(month, hi.date) AS Month,
DATEPART(year, hi.date) AS Year,
COUNT(*) AS 'Total Days'
FROM employee_holiday_item hi
GROUP BY hi.holidayid, DATEPART(month,hi.date), DATEPART(year,hi.date)
Here是一个SQL小提琴。