I have two tables. One table contains events and another table contains effective dates for a bunch of users.
user_id | date_effective | rate
U1 2015-01-01 08.00
U2 2015-01-01 09.00
U1 2015-02-01 10.00
U2 2015-02-01 11.00
U1 2015-03-01 12.00
event_id | date_event
E1 2015-01-15
E2 2015-02-15
E3 2015-03-15
I am pulling a report for every event a specific user is attached to and the effective date for that event for that user. For U1, it would look like this.
event_id | date_event | rate
E1 2015-01-15 08.00
E2 2015-02-15 10.00
E3 2015-03-15 12.00
I am thinking that the effective dates are going to need to be sorted in ascending order so I can pick the first one on a Left Join, which is the default behavior. The problem I am having is that it won't allow me to order the effective dates when doing a Left Join like so:
SELECT event.event_id, event.event_date, effective.rate
FROM event
LEFT JOIN effective ON effective.user_id=U1
ORDER BY effective.date_effective ASC
The other way I tried was to use a comparison operator in the ON clause of the Left Join, but that did not work. Did not really expect it to.
Any suggestions would be deeply appreciated!
Edit Requirements: For any event date, it needs to look backwards and find the first effective date that is before the event date. If there is an event that happens today with an effective date yesterday and an effective date a month ago, the effective date from yesterday should be used.
Did i understand you correctly? You want the first date_effective
by an given user_id
?
With sub-queries:
SELECT *
,date_effecitve = (SELECT top 1 date_effective
FROM effective
WHERE user_id = 'U1'
AND date_effective <= DATE_event
ORDER BY date_effective DESC)
,rate = (SELECT top 1 rate
FROM effective
WHERE user_id = 'U1'
AND date_effective <= DATE_event
ORDER BY date_effective DESC)
FROM event
Result user_id = U1
event_id date_event date_effective rate
E1 15.01.2015 01.01.2015 8
E2 15.02.2015 01.02.2015 10
E3 15.03.2015 01.03.2015 12
Result user_id = U2
event_id date_event date_effective rate
E1 15.01.2015 01.01.2015 9
E2 15.02.2015 01.02.2015 11
E3 15.03.2015 01.02.2015 11
EDIT: Deleted my join-code, because it was noch 100% correct.
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.