尝试这个:
SELECT
o.orderid,
o.userid,
MAX(CASE WHEN c.Name = 'CPU' THEN oc.Value END) AS 'CPU',
MAX(CASE WHEN c.Name = 'Motherboard' THEN oc.Value END) AS 'Motherboard',
MAX(CASE WHEN c.Name = 'Memory' THEN oc.Value END) AS 'Memory'
FROM orders o
INNER JOIN ordercomponents oc ON c.orderid = oc.orderId
INNER JOIN Components c ON oc.componentid = c.componentid
GROUP BY o.orderid, o.userid
请注意:这是执行此操作的标准 SQL 方式。但是您可以使用 SQL ServerPIVOT
表运算符来执行相同的操作,如下所示:
SELECT *
FROM
(
SELECT o.orderid, o.userid, c.Name 'Name', oc.value 'value'
FROM orders o
INNER JOIN ordercomponent oc ON o.orderid = oc.orderId
INNER JOIN Components c ON oc.componentid = c.componentid
) t
PIVOT
(
MAX(value)
FOR Name IN ([CPU], [Motherboard], [Memory])
) p;
但这适用于一组预定义的值,例如[CPU], [Motherboard], [Memory]
.
对于未知数量的值,您必须像这样动态地执行此操作:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.name)
from Components c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT orderid, userid ' + @cols + ' from
(
select o.orderid, o.userid, c.Name Name, oc.value value
FROM orders o
INNER JOIN ordercomponent oc ON o.orderid = oc.orderId
INNER JOIN Components c ON oc.componentid = c.componentid
) x
pivot
(
max(value)
for name in (' + @cols + ')
) p '
execute(@query);