Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group the result from DATEDIFF function in SQL

Tags:

sql

I have this query :

SELECT DATEDIFF(DAY,wj_date,wj_donedate) AS tmpDay
FROM wssjobm , sysbrxces  WHERE wj_br = zu_br AND zu_user = 'mbs' 
AND wj_date >= '2013/04/01' AND wj_date <= '2013/04/30' 
AND wj_status = 'D' AND wj_donedate <= '2013/04/30'

The eg. result :

tmpDay
1
11
5
1
7
2
12
10
2
2

How can i group by the result and count it using query to be like this :

tmpDay count
  1     2
  2     3
  5     1
  7     1
  10    1
  11    1
  12    1

thanks!

Extra Question :

May i get the result like this :

tmpDayGroup Count
   1- 4       5
   5- 8       2
   11 -12     3
like image 757
user2412351 Avatar asked Jan 26 '26 13:01

user2412351


1 Answers

Try:

SELECT 
  tmpDay, 
  COUNT(*) [Count]
FROM 
  YourTable 
Group By tmpDay

For the given example, query should be like:

SELECT 
    DATEDIFF(DAY,wj_date,wj_donedate) AS tmpDay,
    COUNT(*) [Count]
FROM 
    wssjobm , sysbrxces  
WHERE 
    wj_br = zu_br AND 
    zu_user = 'mbs' AND 
    wj_date >= '2013/04/01' AND 
    wj_date <= '2013/04/30' AND 
    wj_status = 'D' AND 
    wj_donedate <= '2013/04/30'
GROUP BY DATEDIFF(DAY,wj_date,wj_donedate)  

For grouping the result, try:

;with T as(
    select '1' FrmD, '4' ToD union all
    select '5' FrmD, '8' ToD union all
    select '9' FrmD, '12' ToD 
)
select 
    T.FrmD +'-'+ T.ToD tmpDayGroup, 
    COUNT(*) [Count] 
from T Left Join (
    SELECT 
        DATEDIFF(DAY,wj_date,wj_donedate) AS tmpDay
    FROM 
        wssjobm , sysbrxces  
    WHERE 
        wj_br = zu_br AND 
        zu_user = 'mbs' AND 
        wj_date >= '2013/04/01' AND 
        wj_date <= '2013/04/30' AND 
        wj_status = 'D' AND 
        wj_donedate <= '2013/04/30'
) T2 on T2.tmpDay between T.FrmD and T.ToD
group by T.FrmD, T.ToD
like image 173
TechDo Avatar answered Jan 28 '26 03:01

TechDo



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!