获取值为true的位列的列名称

时间:2013-05-16 19:54:19

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

我正在尝试创建一个选择查询,如果值为TRUE或1,则返回位列的名称。我唯一能做到的就是如果我添加了一个额外的列“Day”并且描述了day表示可用票证可用的列名称。

我该怎么做?

<cfquery name="getTickets" datasource="test">
SELECT * from tickets
ORDER BY ticketID ASC
</cfquery> 

门票表(解决方法):

ticketID  Monday Tuesday Wednesday Price  Day

1         1      0       0         42.00  Monday
2         0      1       0         42.00  Tuesday
3         0      0       1         42.00  wednesday
4         1      1       1         75.00  All three days

门票表(我想用什么):

ticketID  Monday Tuesday Wednesday Price

1         1      0       0         42.00
2         0      1       0         42.00
3         0      0       1         42.00
4         1      1       1         75.00

2 个答案:

答案 0 :(得分:3)

我强烈建议您在表示层(即客户端)执行此操作。但是,这是一种可能性。

示例数据

create table Tickets(ticketID int, Monday bit, Tuesday bit, Wednesday bit, Price money);
insert into Tickets values (1, 1, 0, 0, 42.00);
insert into Tickets values (2, 0, 1, 0, 42.00);
insert into Tickets values (3, 0, 0, 1, 42.00);
insert into Tickets values (4, 1, 1, 1, 75.00);
insert into Tickets values (5, 0, 0, 0, 15.00);

可能的查询

select *,
       STUFF(
       case when Monday=1 then ',Monday' else '' end
     + case when Tuesday=1 then ',Tuesday' else '' end
     + case when Wednesday=1 then ',Wednesday' else '' end, 1,1,'')
from Tickets;

为了美化边缘情况(“所有三天”和“无”),您可以使用CASE语句

select *,
       CASE WHEN Monday=1and Tuesday=1and Wednesday=1
            THEN 'All three days'
            WHEN Monday=0and Tuesday=0and Wednesday=0
            THEN 'None'
            ELSE
       STUFF(
       case when Monday=1 then ',Monday' else '' end
     + case when Tuesday=1 then ',Tuesday' else '' end
     + case when Wednesday=1 then ',Wednesday' else '' end, 1,1,'')
            END WhichDays
from Tickets;

答案 1 :(得分:0)

尝试UNPIVOT

;with cte as 
(
  SELECT * FROM 
  ( 
    SELECT * FROM tickets 
  ) v
  UNPIVOT
  ( 
    Available FOR Days IN (Monday, Tuesday, Wednesday) 
  ) up
  where Available = 1
)

SELECT ticketid, price, available,
stuff((
    SELECT ', ' + Days
    FROM cte as t1
    where t1.ticketId = t2.TicketId
    FOR XML PATH('')
    ), 1, 2, '')
from cte t2
group by ticketid, price, available;

SQL DEMO