0

这是我的 SQL 语句:

SELECT repnr, DATEDIFF(day, MIN(start), MAX(start) +1) AS DaysTotal
FROM TBLstatus 
WHERE status IN (1, 2, 3, 4, 8, 11, 20, 7, 23)
GROUP BY repnr HAVING COUNT(*) = 2 AND MAX(Start) > GETDATE()-30

Select repnr as repnr, CONVERT(float, SUM(DATEDIFF(day, start, slut))) as extern
From TBLstatus 
where status IN (5, 15, 17)
group by repnr

第一个将返回此数据:

repnr daystotal
1000  100
1001  90
1003  91

第二个声明:

repnr extern
900   100
901   102
1000  21
1003  23

我想要的是 repnr (这是一个 ID)匹配的地方,我想减去 to 值,所以我看起来像这样:

repnr result
1000  79
1003  68

我如何为 MSSQL 执行此操作。

4

3 回答 3

1
SELECT q1.repnr, q1.daystotal - q2.extern as [result]
FROM
(
SELECT repnr, DATEDIFF(day, MIN(start), MAX(start) +1) AS DaysTotal
FROM TBLstatus 
WHERE status IN (1, 2, 3, 4, 8, 11, 20, 7, 23)
GROUP BY repnr HAVING COUNT(*) = 2 AND MAX(Start) > GETDATE()-30
)q1
INNER JOIN 
(
Select repnr as repnr, CONVERT(float, SUM(DATEDIFF(day, start, slut))) as extern
From TBLstatus 
where status IN (5, 15, 17)
group by repnr
)q2 ON q1.repnr = q2.repnr
于 2013-01-29T14:22:59.007 回答
1

将您的查询设置为子查询并加入您的密钥,您应该一切顺利。

select repnr, DaysTotal - extern as result from (SELECT repnr, DATEDIFF(day, MIN(start), MAX(start) +1) AS DaysTotal
FROM TBLstatus 
WHERE status IN (1, 2, 3, 4, 8, 11, 20, 7, 23)
GROUP BY repnr HAVING COUNT(*) = 2 AND MAX(Start) > GETDATE()-30) a inner join (Select repnr as repnr, CONVERT(float, SUM(DATEDIFF(day, start, slut))) as extern
From TBLstatus 
where status IN (5, 15, 17)
group by repnr) b on a.repnr = b.repnr
于 2013-01-29T14:26:59.347 回答
0
SELECT a.repnr, ABS(A.daystotal - b.extern) AS result
FROM(
SELECT repnr, DATEDIFF(day, MIN(start), MAX(start) +1) AS DaysTotal
FROM TBLstatus 
WHERE status IN (1, 2, 3, 4, 8, 11, 20, 7, 23)
GROUP BY repnr HAVING COUNT(*) = 2 AND MAX(Start) > GETDATE()-30
)A
JOIN(
Select repnr as repnr, CONVERT(float, SUM(DATEDIFF(day, start, slut))) as extern
From TBLstatus 
where status IN (5, 15, 17)
group by repnr
)B
ON A.repnr = b.repnr
于 2013-01-29T14:24:04.317 回答