我的SQL Server查询是:
SELECT
ep.employeeID, ep.punchdate, rc.creditAmount
FROM
EmployeePunch ep
INNER JOIN
ResponderCredit rc ON rc.employeeID = ep.employeeID AND
rc.punchdate = rc.creditdate
ORDER BY ep.employeeID
并获得结果集:
EmployeeID Date CreditAmount
----------- ------- --------------
5 01/01/2007 5
5 03/01/2007 7
5 04/22/2007 15
6 01/01/2007 3
6 01/12/2007 4
我想按EmployeeID和Credit金额进行分组。问题是我需要在最大和最小日期之间更改信用额度,所以:
EmployeeID CreditAmount
----------- --------------
5 10
6 1
我该怎么做?
答案 0 :(得分:1)
在Oracle中:
SELECT r1.employeeID, amMax - amMin
FROM (
SELECT employeeID, amMin
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY ep.EmployeeID ORDER BY rc.creditdate) AS rnMin,
ep.employeeID, rc.creditAmount AS amMin
FROM
EmployeePunch ep, ResponderCredit rc
WHERE
rc.employeeID = ep.employeeID
AND rc.punchdate = rc.creditdate
)
WHERE rn_min = 1
) r1,
(
SELECT employeeID, amMin
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY ep.EmployeeID ORDER BY rc.creditdate DESC) AS rnMax,
ep.employeeID, rc.creditAmount AS amMax
FROM
EmployeePunch ep, ResponderCredit rc
WHERE
rc.employeeID = ep.employeeID
AND rc.punchdate = rc.creditdate
)
WHERE rn_max = 1
) r2
WHERE r1.employeeID = r2.employeeID
答案 1 :(得分:0)
对于MS SQL,这应该这样做
SELECT
ep.employeeID, rc.creditAmount,
datediff(month, max(ep.punchdate), min(ep.punchdate))
FROM
EmployeePunch ep
INNER JOIN
ResponderCredit rc ON rc.employeeID = ep.employeeID AND
rc.punchdate = rc.creditdate
group by
EmployeeID, Credit
ORDER BY
ep.employeeID
答案 2 :(得分:0)
这是MSSQL的解决方案。
如果信用额在这段时间内下降,它将显示负值。
它有一些内连接,可能会被优化,但可能不是很多
SELECT maxCredit.employeeID, maxCredit.creditAmount - minCredit.creditAmount FROM ( SELECT ep.employeeID, rc.creditAmount FROM EmployeePunch ep INNER JOIN ResponderCredit rc ON rc.employeeID = ep.employeeID AND rc.punchdate = rc.creditdate INNER JOIN ( SELECT ep2.employeeID, MAX(ep2.punchdate) AS maxCreditdate FROM EmployeePunch ep2 GROUP BY ep2.employeeID ) innermax ON innermax.employeeID = ep.employeeID AND ep.punchdate = innermax.maxcreditDate ) maxCredit INNER JOIN ( SELECT ep.employeeID, rc.creditAmount FROM EmployeePunch ep INNER JOIN ResponderCredit rc ON rc.employeeID = ep.employeeID AND rc.punchdate = rc.creditdate INNER JOIN ( SELECT ep3.employeeID, MIN(ep3.punchdate) AS minCreditdate FROM EmployeePunch ep3 GROUP BY ep3.employeeID ) innermin ON innermin.employeeID = ep.employeeID AND ep.punchdate = innermin.mincreditDate ) minCredit ON maxCredit.employeeID = minCredit.employeeID
答案 3 :(得分:0)
这就是你所期待的我相信......
SELECT
ep.employeeID, Max(datediff(day, ep.punchdate, rc.creditDate)) As [# of Days], rc.creditAmount
FROM
EmployeePunch ep
INNER JOIN
ResponderCredit rc
ON
rc.employeeID = ep.employeeID AND rc.punchdate = rc.creditdate
group by ep.employeeID, rc.creditAmount
ORDER BY ep.employeeID
将产生结果:
EmployeeID # of Days CreditAmount
5 0 5
5 2 7
5 111 15
6 0 3
6 334 4