我有这张桌子(实际桌子要大得多):
id class startdate enddate
----------------------------------------
1 High 1/1/15 2/1/15
1 Low 5/1/15 6/1/15
1 Mid 6/1/15 6/10/15
有没有办法产生如下结果...
id High Mid low
-----------------------
1 30 9 30
我的工作如下......(只是表明我正在尝试解决这个问题)
SELECT DISTINCT --DATEDIFF(DAY, tt.START_DATE,tt.END_DATE)AS Stay_days,
tt.[high], tt.[mid], tt.[low], tt.id,
FROM
(SELECT
[pvt_High], [pvt_mid], [pvt_low], pvt.STARTDATE, pvt.ENDDATE, pvt.id
FROM
(SELECT DISTINCT
l.id, L.class, l.STARTDATE, l.ENDDATE,
DATEDIFF(DAY, l.STARTDATE, l.ENDDATE) AS STAY_DAYS,
'Y' AS Flag
FROM TEST l
WHERE 1=1
PIVOT (MAX(Flag) FOR CLASS IN ([pvt_HIGH], [pvt_MID],[pvt_LOW]))
AS pvt
) tt
答案 0 :(得分:1)
您可以使用内部选择将数据转换为您拥有ID,类和天数的表单。然后,您可以将类值上的数据转换为列。
select *
from
(
select id, class, datediff(day, startDate, endDate) as days
from @test
) x
pivot
(
max(days) for class in (high, low, med)
) y
显然,将名称等更改为适合您数据的内容,这只是一个示例。