3

我有这个查询:

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'

例如。结果 :

tmpDay
1
11
5
1
7
2
12
10
2
2

我如何按结果分组并使用查询对其进行计数,如下所示:

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

谢谢!

额外问题:

我可以得到这样的结果:

tmpDayGroup Count
   1- 4       5
   5- 8       2
   11 -12     3
4

1 回答 1

3

尝试:

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

对于给定的示例,查询应如下所示:

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)  

要对结果进行分组,请尝试:

;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
于 2013-05-23T06:38:09.300 回答