2

我正在尝试创建一个选择查询,如果值为 TRUE 或 1,该查询将返回位列的名称。我能做到的唯一方法是,如果我添加了一个附加列“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
4

2 回答 2

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;
于 2013-05-16T20:07:58.897 回答
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 演示

于 2013-05-16T20:12:41.007 回答