如何选择不同列名的名称是指在表的一行中具有相同值的列的标题?

时间:2017-04-23 14:18:15

标签: mysql sql

表格如下:table name ='seat',列为'seat1','seat2','seat3','seat4','seat5'。

id | seat1 | seat2 | seat3 | seat4 | seat5 
 1 |   0   |   1   |   1   |   0   |   1
 2 |   1   |   1   |   0   |   1   |   0
 3 |   1   |   0   |   1   |   1   |   1

我需要一个sql查询,它为我提供以下查询。当id = 1时,输出将是

seat2, seat3, seat5

如果id = 2,则输出

seat1, seat2, seat4

如果id = 3,则输出

seat1, seat3, seat4, seat5

2 个答案:

答案 0 :(得分:1)

你的意思是这样的吗?如果没有帮助我理解,我可以调整查询逻辑......

  SELECT
        'Occupied Seats = {' +
        CASE WHEN seat1 = 1 THEN '1, ' ELSE '0, ' END +
        CASE WHEN seat2 = 1 THEN '1, ' ELSE '0, ' END +
        CASE WHEN seat3 = 1 THEN '1, ' ELSE '0, ' END +
        CASE WHEN seat4 = 1 THEN '1, ' ELSE '0, ' END +
        CASE WHEN seat5 = 1 THEN '1}' ELSE '0}' END 
    FROM seats 
    WHERE 1 IN (seat1,seat2,seat3,seat4,seat5)

答案 1 :(得分:1)

根据我的理解,你正在寻找只占用的座位。我基于这种理解准备了以下查询。如果理解存在差距,请评论:

select * from 
(
select 'seat1', seat1 as occupiedStatus from [table]
union
select 'seat2', seat2 as occupiedStatus from [table]
union
select 'seat3', seat3 as occupiedStatus from [table]
union
select 'seat4', seat4 as occupiedStatus from [table]
union
select 'seat5', seat5 as occupiedStatus from [table]
) seatsPivot
where occupiedStatus = 1 ;