我最近问了一个类似的问题但不幸的是,请求的性质发生了变化。一直在看这段代码,但我的大脑是朋友,我无法想到一种方法让它按需运行。
在SQL 2005中工作,这将包含数百个这样的值。
提前致谢!
样本表
+----+-------------+---------------------+---------------------+
| ID | CLASS | PARENT_ATTRIBUTE | ATTRIBUTE |
+----+-------------+---------------------+---------------------+
| 1 | Genre | A | Hip Hop |
| 1 | Genre | B | Pop |
| 1 | Instruments | Keyboards | Synth |
| 1 | Instruments | Keyboards | Grand Piano |
| 1 | Instruments | Drums | Kit |
| 1 | Moods | Positive/Optimistic | Uplifting/Inspiring |
| 1 | Moods | Positive/Optimistic | Happy/Feel Good |
| 1 | Moods | Musical Feel | Pulsing |
+----+-------------+---------------------+---------------------+
期望输出
+----+----------------------------------------------------------------------------------------------------------+---------------------------------------------------------+
| ID | MOODS | INSTRUMENTS |
| 1 |Positive/Optimistic - Uplifting/Inspiring, Positive/Optimistic - Happy/Feel Good, Musical Feel - Pulsing | Keyboards - Synth, Keyboards - Grand Piano, Drums - Kit |
+----+----------------------------------------------------------------------------------------------------------+---------------------------------------------------------+
答案 0 :(得分:0)
使用MAX和CASE WHEN的技巧将类放入列中:
SELECT ID,
MAX(CASE WHEN class = 'Instruments' THEN attribs END) as INSTRUMENTS,
MAX(CASE WHEN class = 'Moods' THEN attribs END) as MOODS,
MAX(CASE WHEN class = 'Genre' THEN attribs END) as GENRES
FROM (
SELECT
id, class,
STUFF ((
SELECT ', ' + parent_attribute + ' - ' + attribute
FROM YourTable i
WHERE i.ID = o.ID AND i.CLASS = o.CLASS
FOR XML PATH('')
), 1, 2, '') AS attribs
FROM (SELECT DISTINCT id, class FROM YourTable) o
) q
GROUP BY id
ORDER BY id;
或者,在SQL Server 2008或更高版本上使用PIVOT:
select ID,
[Instruments] as INSTRUMENTS,
[Moods] as MOODS,
[Genre] as GENRES
from (
SELECT id, class,
STUFF ((
SELECT ', ' + parent_attribute + ' - ' + attribute
FROM YourTable i
WHERE i.ID = o.ID AND i.CLASS = o.CLASS
FOR XML PATH('')
), 1, 2, '') AS attribs
FROM (select distinct id, class from YourTable) o
) q
PIVOT (MAX(attribs) FOR class IN ([Instruments], [Moods], [Genre])
) pvt
order by id;
答案 1 :(得分:-1)
也许使用PIVOT你可以输出,但我真的不知道如何......
检查此链接: https://technet.microsoft.com/library/ms177410(v=sql.105).aspx