使用SQL Server 2008,查找一个表但查找特定输出。当前表,名为fmCalendar:
>Date Calendar Days
>12/30/2014 Canada 1
>12/30/2014 Europe 1
>12/30/2014 UK 1
>12/30/2014 US 1
>12/29/2014 Canada 2
>12/29/2014 Europe 2
>12/29/2014 UK 3
>12/29/2014 US 3
>...
我希望输出看起来像这样:
>Date Canada Europe UK US
>12/30/2014 1 1 1 1
>12/29/2014 2 2 3 3
>...
我该怎么做?提前致谢
答案 0 :(得分:0)
我会查询它
select
Date,
Sum(case when Calendar = 'Canada' then Days else 0 end) as Canada,
Sum(case when Calendar = 'Europe' then Days else 0 end) as Europe,
Sum(case when Calendar = 'UK' then Days else 0 end) as UK,
Sum(case when Calendar = 'US' then Days else 0 end) as Us,
Sum(case when Calendar not in ('Canada','Europe','UK','US') then Days else 0 end)
as Other
from
MyTable
group by
Date
答案 1 :(得分:0)
您可以执行PIVOT
:
SELECT *
FROM fmCalendar AS T
PIVOT(SUM([days]) FOR Calendar IN ([Canada],[Europe],[UK],[US])) AS P
带有演示的Here is an sqlfiddle。结果是:
╔═══════════════════╦════════╦════════╦════╦════╗
║ DATE ║ CANADA ║ EUROPE ║ UK ║ US ║
╠═══════════════════╬════════╬════════╬════╬════╣
║ December, 29 2014 ║ 2 ║ 2 ║ 3 ║ 3 ║
║ December, 30 2014 ║ 1 ║ 1 ║ 1 ║ 1 ║
╚═══════════════════╩════════╩════════╩════╩════╝