从一行中的同一个表中选择多值

时间:2017-11-15 12:51:05

标签: sql sql-server

我有下表。作为系统中值的参考表。

Item    Item_code
Turkey  c01
KSA     c02
USA     c03
NY      s01
JED     s03
Dubai   j01
London  j02
.       .
.       .
.       .

在用户的显示页面中,我想显示可读数据" KSA, NY ..."不是代码。将结果放在一行会节省很多代码行。我不想做5个select语句来分别获取每个值

示例:我想在一行中显示c02, s01 and s03的项目列。

期望的结果:

first Item     second Item    third Item ...
KSA             JED           NY

这适用于5列。

3 个答案:

答案 0 :(得分:4)

一种方法使用带有ANSI标准row_number()函数的条件聚合:

select max(case when seqnum = 1 then item end) as item_1,
       max(case when seqnum = 2 then item end) as item_2,
       max(case when seqnum = 3 then item end) as item_3,
       max(case when seqnum = 4 then item end) as item_4,
       max(case when seqnum = 5 then item end) as item_5
from (select t.*, row_number() over (order by item_code) as seqnum
      from t
       where item_code in ('c02', 's01', 's03')
     ) t;

答案 1 :(得分:2)

条件MAX()

怎么样?
 SELECT MAX( CASE WHEN Item_code = 'c02' THEN Item END ) as first_item,
        MAX( CASE WHEN Item_code = 's01' THEN Item END ) as second_item,
        MAX( CASE WHEN Item_code = 's03' THEN Item END ) as third_item
 FROM Items

答案 2 :(得分:2)

您可以使用像这样的数据透视表

select * from (
    select item, code from @table
) as x
pivot
(
    max(item)
    for code in (c02, s03, s01)
) as pvt