我最近问了一个类似的问题,但不幸的是,请求的性质发生了变化。我已经看了这段代码一段时间了,但我的大脑是朋友,我想不出一种方法让它按需工作。
在SQL2005中工作,这将包含数百个这样的值。
提前感谢!
示例表
+----+-------------+---------------------+---------------------+
| 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 |
+----+----------------------------------------------------------------------------------------------------------+---------------------------------------------------------+发布于 2016-10-12 22:47:08
在将类放入列时使用MAX和CASE的技巧:
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;发布于 2016-10-12 03:48:11
也许使用PIVOT你可以得到这样的输出,但我真的不知道如何……
请查看此链接:https://technet.microsoft.com/library/ms177410(v=sql.105).aspx
https://stackoverflow.com/questions/39985341
复制相似问题