简体   繁体   English

从SQL抓取/重新排列表数据

[英]Grabbing/rearranging data from SQL for table

I have data in sql that looks like so: 我在sql中有如下数据:

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. 我对SQL完全陌生,因此非常感谢您提供任何帮助和相关链接来解释答案。

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 SQL FIDDLE DEMO

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 SQL小提琴示例

This is basically a poor man's pivot table, which should work on most RDBMS. 从根本上讲,这是一个穷人的数据透视表,可以在大多数RDBMS上使用。 What it does is use a SUM with a CASE to achieve a count-if for each month. 它的作用是使用带有CASE的SUM来实现每月的if-if。 That is, for January, the value for each row will be 1 if Month = '01', or 0 otherwise. 也就是说,对于一月,如果Month ='01',则每一行的值为1,否则为0。 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. GROUP BY Level子句告诉引擎为Level每个不同值生成一个结果行,从而将数据按不同级别分开。


Since you are using SQL Server 2005, which supports PIVOT , you can simply do: 由于您正在使用支持PIVOT SQL Server 2005,因此只需执行以下操作:

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 SQL小提琴示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM