I have two tables, namely Employees and Payments. Below is the contents of the two:
The Employees table
EmpID |EmpName
------ --------
113 Harry
The Payments table
EmpID | Amount | Period | PaymentType | St
------------------------------------------
------------------------------------------
113 | 100 | 201207 | 1 | 1
------------------------------------------
113 | 70 | 201206 | 1 | 0
------------------------------------------
113 | 120 | 201207 | 1 | 0
------------------------------------------
113 | 200 | 201207 | 1 | 1
------------------------------------------
113 | 90 | 201207 | 2 | 1
------------------------------------------
Here's my query:
SELECT EMP.EMPID ID, PAID_TOTAL,PAID_CURRENT,PAID_PAST,PAID_OT
FROM EMPLOYEES EMP
, (
SELECT EMPID,SUM(AMOUNT)PAID_TOTAL
FROM PAYMENTS
WHERE PERIOD<='201207' AND ST=1
GROUP BY EMPID
)
PY_TOTAL, (
SELECT EMPID,SUM(AMOUNT)PAID_CURRENT
FROM PAYMENTS
WHERE PERIOD='201207' AND PAYMENTTYPE=1 AND ST=1
GROUP BY EMPID
)
PY_CURRENT, (
SELECT EMPID,SUM(AMOUNT)PAID_PAST
FROM PAYMENTS
WHERE PERIOD<'201207' AND PAYMENTTYPE=1 AND ST=1
GROUP BY EMPID
)
PY_PAST, (
SELECT EMPID,SUM(AMOUNT)PAID_OT
FROM PAYMENTS
WHERE PERIOD='201207' AND PAYMENTTYPE=2 AND ST=1
GROUP BY EMPID
)
PY_OT
WHERE
(
EMP.EMPID=PY_TOTAL.EMPID OR EMP.EMPID=PY_CURRENT.EMPID OR
EMP.EMPID=PY_PAST.EMPID OR EMP.EMPID=PY_OT.EMPID
);
What I would expect to get is:
ID | PAID_TOTAL | PAID_CURRENT | PAID_PAST | PAID_OT
113 460 300 70 90
But no row is returned from the above query.
Period
, is it datetime? That would explain one of the derived tables to have no rows in the result - and thus the whole query as well. Try running each derived table individually.OR
should beAND
(and then converted to explicitJOIN
s).200 x 1200 x 645 x 0 x 179
. Multiplication by 0 has this nice effect. Convert the query to useLEFT JOIN
instead. Which DBMS do you use?