Domanda

Using SQL Server 2008, looking to query one table but looking for specific output. Current table, named 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
>...

I'd like the output to look like this:

>Date       Canada  Europe  UK  US
>12/30/2014 1       1       1   1
>12/29/2014 2       2       3   3
>...

How do I do this? Thanks in advance

È stato utile?

Soluzione

I would query it like

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

Altri suggerimenti

You can do a PIVOT:

SELECT *
FROM fmCalendar AS T
PIVOT(SUM([days]) FOR Calendar IN ([Canada],[Europe],[UK],[US])) AS P

Here is an sqlfiddle with a demo. The results are:

╔═══════════════════╦════════╦════════╦════╦════╗
║       DATE        ║ CANADA ║ EUROPE ║ UK ║ US ║
╠═══════════════════╬════════╬════════╬════╬════╣
║ December, 29 2014 ║      2 ║      2 ║  3 ║  3 ║
║ December, 30 2014 ║      1 ║      1 ║  1 ║  1 ║
╚═══════════════════╩════════╩════════╩════╩════╝
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top