我从来没有做过这样的事情,我尝试在谷歌上找到它但没有结果。
我有3个表格如下:
订单
OdredID (int) PK,
UserID (int) FK,
OdredDate (datetime)
组件:
ComponentID (int) PK,
Name (nvarchar(50)),
Type (nvarchar(max))
OrderComponent:
OrderComponentID (int) PK,
OrderID (int) FK,
ComponentID (int) FK,
Value (nvarchar(max))
假设一个订单有3个组件,其名称为:[CPU, Motherboard, Memory]
和值[1GHz, AsusP5, 2GB Kingston DDR3]
我需要一个像这样的列的结果:
OrderID UserID Date CPU Motherboard Memory
1 1 2012-05-21 1GHz AsusP5 2GB Kingston DDR3
基本上我需要每个连接行作为新列,其名称取自联接表的Name
列和Value
列的值。
答案 0 :(得分:3)
试试这个:
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 Server PIVOT
表运算符执行相同的操作:
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);