简体   繁体   中英

SQL Join same table based on other tables

I have a payment table, related to dates table and event table. I made separated queries with the result I want:

SELECT employee_id, payment.value ADDITIONAL
FROM payment
INNER JOIN dates ON payment.date_id = dates.id
INNER JOIN event ON payment.event_id = event.id 
WHERE date = '03-2021'
    AND employee_id = 71
    AND event.number = 10015


SELECT employee_id, payment.value SALARY
FROM payment
INNER JOIN dates ON payment.date_id = dates.id
INNER JOIN event ON payment.event_id = event.id 
WHERE date = '03-2021'
    AND employee_id = 71
    AND event.number = 4096

This basically gives this result:

结果

What I want is this result in same row for this emplyee:

想要的结果

You can do it with conditional aggregation:

SELECT p.employee_id, 
       MAX(CASE WHEN e.number = 10015 THEN p.value END) additional,
       MAX(CASE WHEN e.number = 4096 THEN p.value END) salary
FROM payment p
INNER JOIN dates d ON p.date_id = d.id
INNER JOIN event e ON p.event_id = e.id 
WHERE d.date = '03-2021' AND p.employee_id = 71
  AND e.number IN (10015, 4096)
GROUP BY p.employee_id

Note that you should qualify all the columns with the table's name/alias they belong to. In your query, I assume that employee_id is a column in payment and date is a column in dates .

change to

SELECT t1.employee_id, t1.payment.additional,t2.SALARY
FROM
(SELECT employee_id, payment.additional
FROM payment
INNER JOIN dates ON payment.date_id = dates.id
INNER JOIN event ON payment.event_id = event.id 
WHERE date = '03-2021'
    AND employee_id = 71
    AND event.number = 10015) t1
    
JOIN 

(SELECT employee_id, payment.salary SALARY
FROM payment
INNER JOIN dates ON payment.date_id = dates.id
INNER JOIN event ON payment.event_id = event.id 
WHERE date = '03-2021'
    AND employee_id = 71
    AND event.number = 4096) t2
ON t1.employee_id = t2.employee_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM