对不起,如果标题太可怕了。有一个表T.列名称,数字和状态包含I,O或S.
例如:
Name Num Status
Bob 1 I
Bob 2 O
Bob 3 O
John 4 I
John 5 S
Joe 6 O
希望结果如下:
Name Num I O S
Bob 1 x
Bob 2 x
Bob 3 X
John 4 X
John 5 X
谢谢!
编辑:跟进问题。
Name Num I O S
Bob 1 x
Bob 1 x
Bob 2 X
需要结果:
Name Num I O S
Bob 1 X X
Bob 2 X
编辑2:实际查询:
SELECT Name, Card_Nmbr,
[Out] = case when d.Status='I' then 'X' else '' end,
[In] = case when d.Status='O' then 'X' else '' end,
[Sales] = case when d.Status='S' then 'X' else '' end
FROM [PCOdb].[dbo].[GC_Header] as h
INNER JOIN GC_Detail as d on h.GC_TransNmbr = d.GC_TransNmbr
INNER JOIN GC_Master as m on d.GCM_Nmbr = m.GCM_Nmbr
INNER JOIN Galaxy1.dbo.GxUsers as u on h.UserID = u.UserID
WHERE GC_TransDate between '11/29/16' and dateadd(day,1, '11/29/16')
Group BY Card_Nmbr, Name
答案 0 :(得分:2)
一个简单的案例陈述将有助于
Select Name
,Num
,[I] = case when [Status]='I' then 'X' else '' end
,[O] = case when [Status]='O' then 'X' else '' end
,[S] = case when [Status]='S' then 'X' else '' end
From YourTable
EDIT处理多行
Select Name
,Num
,[I] = max(case when [Status]='I' then 'X' else '' end)
,[O] = max(case when [Status]='O' then 'X' else '' end)
,[S] = max(case when [Status]='S' then 'X' else '' end)
From YourTable
Group By Name,Num
编辑2 - 完整查询(假设联接正在执行您需要的操作)
SELECT Name
,Card_Nmbr
,[Out] = max(case when d.[Status]='I' then 'X' else '' end)
,[In] = max(case when d.[Status]='O' then 'X' else '' end)
,[Sales] = max(case when d.[Status]='S' then 'X' else '' end)
FROM [PCOdb].[dbo].[GC_Header] as h
JOIN GC_Detail as d on h.GC_TransNmbr = d.GC_TransNmbr
JOIN GC_Master as m on d.GCM_Nmbr = m.GCM_Nmbr
JOIN Galaxy1.dbo.GxUsers as u on h.UserID = u.UserID
WHERE GC_TransDate between '2016-11-29' and DateAdd(DD,1,'2016-11-29')
Group BY Card_Nmbr, Name
答案 1 :(得分:1)
使用Case表达式。
<强>演示:强>
Create table #temp
(Name varchar (10),
Num int ,
[Status] char(1))
insert into #temp values ('Bob' , '1' , 'I')
insert into #temp values ('Bob' , '2' , 'O')
insert into #temp values ('Bob' , '3' , 'O')
insert into #temp values ('John' , '4' , 'I')
insert into #temp values ('John' , '5' ,'S')
insert into #temp values ('Joe' , '6' , 'O')
select Name,
Num,
[I] = case
when [Status] ='I'
then 'X'
else ''
end
,[O] = case
when [Status] ='O'
then 'X'
else ''
end
,[S] = case when [Status] ='S'
then 'X'
else ''
end
from #temp
drop table #temp
<强>结果:强>
答案 2 :(得分:0)
对于SQL Server 2012及更高版本,您也可以使用IIF (Transact-SQL)
功能。
Select Name
,Num
,IIF([Status] = 'I' , 'X', '' ) AS [I]
,IIF([Status] = 'O' , 'X', '' ) AS [O]
,IIF([Status] = 'S' , 'X', '' ) AS [S]
FROM TableName