aseolin
aseolin

Reputation: 1200

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:

result

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

wanted result

Upvotes: 1

Views: 55

Answers (2)

forpas
forpas

Reputation: 164099

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.

Upvotes: 2

persian-theme
persian-theme

Reputation: 6638

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

Upvotes: 0

Related Questions