Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional group by in sql server?

i have this simple query :

SELECT YEAR(P.DateCreated)
      ,MONTH(P.DateCreated)
      ,COUNT(*) AS cnt
FROM   tbl1,
       tbl2....
GROUP BY
         MONTH(P.DateCreated)
        ,YEAR(P.DateCreated)

this will emit :

enter image description here

now i need the same query but with groupby only per year :

so :

SELECT YEAR(P.DateCreated)

      ,COUNT(*) AS cnt
FROM   tbl1,
       tbl2....
GROUP BY
         YEAR(P.DateCreated)

i dont want to make 2 queries.

is there any way i can do conitional group by here ?

i can do with one being replaced by another , but i cant do one being replaced by two...

GROUP BY
     CASE WHEN @timeMode='y' THEN YEAR(P.DateCreated)
          WHEN @timeMode='m' THEN MONTH(P.DateCreated), YEAR(P.DateCreated) end

enter image description here

any help ?

like image 670
Royi Namir Avatar asked Jun 24 '12 12:06

Royi Namir


2 Answers

You would be better off with two separate queries but can do it like

GROUP BY YEAR(P.DateCreated),
       CASE 
          WHEN @timeMode='m' THEN MONTH(P.DateCreated) end

As WHEN @timeMode <> 'm' the second GROUP BY expression will be NULL for all rows and not affect the result.

like image 102
Martin Smith Avatar answered Sep 30 '22 09:09

Martin Smith


You could use an over clause to return both the per-yearly and the per-month count in one query:

SELECT  distinct YEAR(P.DateCreated) as Year
,       MONTH(P.DateCreated) as Month
,       COUNT(*) over (partition by YEAR(P.DateCreated), MONTH(P.DateCreated)) 
            as MonthCount
,       COUNT(*) over (partition by YEAR(P.DateCreated)) as YearCount
FROM   YourTable P

Live example at SQL Fiddle.

like image 37
Andomar Avatar answered Sep 30 '22 08:09

Andomar