EvilWeebl
EvilWeebl

Reputation: 701

Grabbing/rearranging data from SQL for table

I have data in sql that looks like so:

Month  PersonID  Level 
 01       102      2
 01       506      1
 02       617      3
 02       506      1
 03       297      2

And I need to query this data to receive it for use in a table that would look like this

         Jan  Feb  March ...etc
Level 1
Level 2
Level 3

with the values being how many people are in each level each month.

I'm a complete noob with SQL so any help and relevant links to explain answers would be much appreciated.

Upvotes: 0

Views: 147

Answers (2)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Try this:

SELECT 'Level' + CAST(level as varchar), [January], [February], [March]
FROM (SELECT DATENAME(month, '2013'+Month+'01') Month, PersonID, Level FROM Tbl) T
PIVOT
(
  COUNT(PersonID) FOR Month IN ([January], [February], [March])

) A

SQL FIDDLE DEMO

Upvotes: 3

lc.
lc.

Reputation: 116528

SELECT 'Level ' + CAST("Level" AS VARCHAR(2)),
    SUM(CASE Month WHEN '01' THEN 1 ELSE 0 END) AS Jan,
    SUM(CASE Month WHEN '02' THEN 1 ELSE 0 END) AS Feb,
    SUM(CASE Month WHEN '03' THEN 1 ELSE 0 END) AS Mar,
    ...

FROM myTable
GROUP BY "Level"

SQL Fiddle Example

This is basically a poor man's pivot table, which should work on most RDBMS. What it does is use a SUM with a CASE to achieve a count-if for each month. That is, for January, the value for each row will be 1 if Month = '01', or 0 otherwise. Summing these values gets the total count of all "January" rows in your table.

The GROUP BY Level clause tells the engine to produce one result row for each distinct value in Level, thus separating your data by the different levels.


Since you are using SQL Server 2005, which supports PIVOT, you can simply do:

SELECT 'Level ' + CAST("Level" AS VARCHAR(2)), 
    [01] AS [Jan], [02] AS [Feb], [03] AS [Mar], ...
FROM myTable
PIVOT
(
    COUNT(PersonId)
    FOR Month IN ([01], [02], [03], ...)
) x

SQL Fiddle Example

Upvotes: 2

Related Questions