SQL Server:从子查询中调出列

时间:2014-09-17 14:57:01

标签: sql sql-server-2008-r2 unpivot

我对此非常感兴趣(SQL Server 2008 R2)。

我有一个名为orders的表:

Orders

orderid  details
--------------------
1        my order

然后我有一个自定义字段表。

Custom_fields

rel_orderid  fieldname  numericvalue  textvalue  datevalue
-----------------------------------------------------------
1            auction    0             My auction
1            date       0                        01/01/2014

我想要

orderid   details   auction     date (on one row)
-------------------------------------------------
1         my order  my auction  01/01/2014

希望这是有道理的,但我打败了如何将custom_fields表包装到列标题中然后只有1个值(可能是文本值或日期等 - 只有1个会有数据)< / p>

拍卖和日期并从字段名列中读取,然后读取每个字段的值。

3 个答案:

答案 0 :(得分:0)

您可以将maxcase一起使用:

select o.orderid, 
       o.details, 
       max(case when c.fieldname = 'auction' then textvalue end) auction,
       max(case when c.fieldname = 'date ' then datevalue end) datevalue 
from orders o
       join custom_fields c on o.orderid = c.rel_orderid  
group by o.orderid

答案 1 :(得分:0)

你可以在这种情况下陷入困境。

select orderid,
       details,
       [auction],  
       [date]
FROM
(
      select rel_orderid as orderid,
             o.details, 
             fieldname, 
             (case when fieldname = 'auction'
                     then textvalue
                     when fieldname ='date' 
                     then cast(datevalue AS varchar(128))
                     end) value
       FROM custom_fields
       INNER JOIN orders o
       on o.orderid = rel_orderid
) As OrderDetails 
PIVOT
(
        max(value) 
        for fieldname in ([auction],[date])
) pvt

答案 2 :(得分:0)

如果要避免聚合,可以使用连接执行此操作:

select o.orderid, o.details, a.textvalue as auction, d.datevalue as dateval
from orders o left join
     custom_fields a
     on a.rel_orderid = o.orderid and a.fieldname = 'auction' left join
     custom_fields d
     on d.rel_orderid = o.orderid and d.fieldname = 'date';

即使没有匹配,left join也会给出一个值(NULL)。