我正在尝试根据sum(rtime-time)计算> = 1 OR< = -1的行数。
我的表
aono | aopos | artno | flogr | prgr | rtime | time | rdate |
7132 | 10 | 1234 | 20 | 20 | 2 | 1 | 2017-08-24 |
7132 | 10 | 1234 | 30 | 30 | 1,3 | 1 | 2017-08-24 |
7132 | 20 | 5678 | 20 | 29 | 1 | 3 | 2017-08-24 |
7132 | 20 | 5678 | 30 | 31 | 0,4 | 1,5 | 2017-08-24 |
7132 | 50 | 12 | 10 | 10 | 0,5 | 0,5 | 2017-08-24 |
我已经提出了这个问题。
SELECT aono, aopos, artno, flogr, prgr, sum(rtime-time) AS Diff
FROM dbo.ao
WHERE (rdate Between '2017-08-01' AND '2017-08-31') AND (flogr = '20' OR flogr = '30')
GROUP BY aono, aopos, artno, flogr, prgr
HAVING SUM(rtime-time) >= '1' OR SUM(rtime-time) <= '-1'
返回以下结果
aono | aopos | artno | flogr | prgr | Diff
7132 | 10 | 1234 | 20 | 20 | 1
7132 | 20 | 5678 | 20 | 29 | -2
7132 | 20 | 5678 | 30 | 31 | -1,1
所以我需要帮助的是创建一个根据上面的查询计算行数(Diff)的查询。在这个例子中,正确的结果是3。
提前致谢
/ SisU
答案 0 :(得分:4)
你几乎只使用COUNT
SELECT COUNT(*)
FROM
(
SELECT aono, aopos, artno, flogr, prgr, sum(rtime-time) AS Diff
FROM dbo.ao
WHERE (rdate Between '2017-08-01' AND '2017-08-31') AND (flogr = '20' OR flogr = '30')
GROUP BY aono, aopos, artno, flogr, prgr
HAVING SUM(rtime-time) >= '1' OR SUM(rtime-time) <= '-1')
) t
答案 1 :(得分:2)
您需要在查询中运行COUNT
SELECT COUNT(*) FROM
(SELECT aono, aopos, artno, flogr, prgr, sum(rtime-time) AS Diff
FROM dbo.ao
WHERE (rdate Between '2017-08-01' AND '2017-08-31')
AND (flogr = '20' OR flogr = '30')
GROUP BY aono, aopos, artno, flogr, prgr
HAVING SUM(rtime-time) >= '1' OR SUM(rtime-time) <= '-1')