从2选择语句输出不同的列

时间:2013-12-26 06:21:07

标签: sql-server row

我希望实现类似的目标;

例如

ID  VALUE NAME
1   1234  COUNTER
2   1235  BAGGAGE

输出:

COUNTER BAGGAGE
1234    1235

脚本:

SELECT ID, VALUE, NAME FROM table WHERE ID = 1
UNION ALL
SELECT ID, VALUE, NAME FROM table WHERE ID = 2

结果:

ID  VALUE NAME
1   1234  COUNTER
2   1235  BAGGAGE

这是一个行到列的方法吗?

4 个答案:

答案 0 :(得分:0)

试试这个::

select id,case when name='counter' then value else ' ' end as counter,

        case when name='baggage' then value else ' ' end as baggage

        from table

输出

  id  counter baggage
   1   1234
   2           1235

fiddle demo

答案 1 :(得分:0)

在这种情况下,您使用以下查询。它不是非常通用,但在特定情况下可能就足够了,因为它简单易用。

select 
(select top 1 value from yourtable where name = 'counter') as counter,
(select top 1 value from yourtable where name = 'baggage') as baggage

SQL Fiddle demo

答案 2 :(得分:0)

您可以像这样使用PIVOT

DECLARE @DataSource TABLE
(
   [ID] TINYINT
  ,[VALUE] SMALLINT
  ,[Name] VARCHAR(12)
)

INSERT INTO @DataSource ([ID],[VALUE],[Name])
VALUES (1,1234,'COUNTER')
      ,(2,1235,'BAGGAGE')     

SELECT  [COUNTER]
       ,[BAGGAGE]
FROM 
(
    SELECT [VALUE]
          ,[Name]
    FROM @DataSource 
) AS DS
PIVOT
(
  MAX([VALUE]) FOR [Name] IN ([COUNTER], [BAGGAGE])
) AS PVT

输出:

enter image description here

检查example

答案 3 :(得分:0)

另一个标准解决方案

select max(case when name='counter' then value end) as counter,

       max(case when name='baggage' then value end) as baggage

from table