Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bucketing data in SQL Server 2008

I am starting with data that looks like this:

+----------+------------------+--------+
| 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 |
+----------+------------------+--------+

I would like to know whether it is possible to transform it to a frequency distribution like this:

enter image description here

Would I use the pivot function in SQL Server? If so, how?

Please note that I do have access to SSRS, and can use that as a resource to tackle this challenge.

Thanks so much for your guidance and time

like image 690
Alex Gordon Avatar asked Sep 27 '26 09:09

Alex Gordon


1 Answers

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
like image 85
Quassnoi Avatar answered Sep 30 '26 03:09

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!