我有这个问题:
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
答案 0 :(得分: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