在SQL Server 2008中暂停数据

时间:2012-05-22 20:46:29

标签: sql sql-server sql-server-2008

我开始使用如下所示的数据:

+----------+------------------+--------+
| specimen |       date       | bucket |
+----------+------------------+--------+
| 31598D   | 3/3/2010 11:38   |     10 |
| A113899  | 2/10/2010 13:50  |     11 |
| A121375  | 12/17/2010 10:06 |      2 |
| A122115  | 6/14/2010 9:33   |     10 |
| A122119  | 5/19/2010 10:08  |      3 |
| A122124  | 6/30/2010 11:43  |      4 |
| DD58834  | 6/17/2010 10:08  |      1 |
| 31598A   | 3/3/2010 11:36   |     10 |
+----------+------------------+--------+

我想知道是否可以将其转换为这样的频率分布:

enter image description here

我会在SQL Server中使用pivot函数吗?如果是这样,怎么样?

请注意,我确实可以访问SSRS,并可以将其用作解决此挑战的资源。

非常感谢您的指导和时间

3 个答案:

答案 0 :(得分:3)

WITH    bm (maxbucket) AS
        (
        SELECT  MAX(bucket)
        FROM    mydata
        ),
        buckets (bucket) AS
        (
        SELECT  1
        UNION ALL
        SELECT  bucket + 1
        FROM    buckets
        JOIN    bm
        ON      bucket < maxbucket
        )
SELECT  bucket, p.*
FROM    (
        SELECT  b.bucket, DATEPART(month, dt) AS mon
        FROM    buckets b
        LEFT JOIN
                mydata m
        ON      m.bucket = b.bucket
        ) q
PIVOT   (
        COUNT(mon)
        FOR
        mon IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
        ) p

答案 1 :(得分:1)

select * from t
pivot (
        count (*) for datepart(m, date) 
        in ([01],[02],[03],[04],[05],
            [06],[07],[08],[09],[10],[11],[12])
) as CountSpec

试试

答案 2 :(得分:1)

这是未经测试的,因为我没有方便的SQL Server实例,但它应该说明这个想法;您可以在case语句上使用SUM()来生成所需的分发。

SELECT
      [bucket]
    , SUM( CASE WHEN DATEPART(MONTH,[date]) = 1 THEN 1 ELSE 0 END ) AS [Jan]
    -- repeat the above for each month
FROM
    [your_table]
GROUP BY
    [bucket]
ORDER BY
    [bucket] DESC