6

嗨我有两个表属性,实例

属性表

id  |    key_info   |   value_info
2   |     amount    |    1009
2   |   currency    |     USD
2   |     Level     |    Level 5
3   |    amount     |     2017 
3   |   currency    |     CAD

实例表

id   |  status
2    | Pending 
3    | Approved

我想像这样加入两张桌子-

新表

id | amount |  currrency | level   | status
2  |  1001  |     USD    | Level 5 | Pending
3  |   2017 |     CAD    |         | Approved

Attribute 和 Instance 中的所有字段都是可选的,除了 id。

4

2 回答 2

13
select
  a.id,
  max(case when a.key_info = 'amount' then a.value_info end) as amount,
  max(case when a.key_info = 'currency' then a.value_info end) as currency,
  max(case when a.key_info = 'level' then a.value_info end) as level,
  i.status
from
  attribute a
  join instance i on a.id = i.id
group by
  a.id,
  i.status

Sql 小提琴

于 2013-03-05T21:20:26.073 回答
9

从 SQL Server 2005 开始,该PIVOT函数可以执行从行到列的这种转换:

select id, 
  amount, 
  currency, 
  level,
  status
from 
(
  select i.id, i.status,
    a.key_info,
    a.value_info
  from instance i
  inner join attribute a
    on i.id = a.id
) src
pivot
(
  max(value_info)
  for key_info in (amount, currency, level)
) piv

请参阅SQL Fiddle with Demo

如果您的数量未知,key_values则可以使用动态 SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(key_info) 
                    from Attribute
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id, ' + @cols + ', status from 
             (
                select i.id, i.status,
                  a.key_info,
                  a.value_info
                from instance i
                inner join attribute a
                  on i.id = a.id
            ) x
            pivot 
            (
                max(value_info)
                for key_info in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo。两者都给出结果:

| ID | AMOUNT | CURRENCY |   LEVEL |   STATUS |
-----------------------------------------------
|  2 |   1009 |      USD | Level 5 |  Pending |
|  3 |   2017 |      CAD |  (null) | Approved |
于 2013-03-05T22:14:49.333 回答