I have got two tables:
- tbl_sms
- tbl_bids
The above two table holds something like this:
tbl_sms:
Post_ID | User_ID | SMS_Sent_DT
---------------------------------
123 | 007 | 2010-05-14 10:15:25
123 | 008 | 2010-05-14 10:18:32
123 | 009 | 2010-05-14 10:23:05
123 | 010 | 2010-05-14 10:23:06
tbl_bids:
Post_ID | User_ID | Bid_DT
--------------------------
123 | 010 | 2010-05-14 10:27:25
123 | 008 | 2010-05-14 10:28:32
123 | 009 | 2010-05-14 10:28:47
123 | 007 | 2010-05-14 10:35:06
With those two tables I'm trying to achieve the following:
Post_ID | First_BID_Time | First_BID_SMS_TIME | Second_BID_Time | Second_BID_SMS_Time | Third_BID_Time | Third_BID_SMS_Time
-----------------------------------------------------------------------------------------------------------------------------------
123 | 2010-05-14 10:27:25 | 2010-05-14 10:23:06 | 2010-05-14 10:28:32 | 2010-05-14 10:18:32 | 2010-05-14 10:28:47 | 2010-05-14 10:23:05
The query I had written is:
SELECT b.post_id,
sms.message_sent_at as notif_sent1,
b.message_sent_at as notif_accepted1,
DATEDIFF(b.message_sent_at, sms.message_sent_at) AS delay1
FROM tbl_bids b
LEFT JOIN tbl_sms_status sms ON (sms.jobid = b.post_id AND b.user_id = sms.userid)
WHERE b.post_id = sms.jobid
ORDER BY b.post_id ASC
That gives me the correct result but they are not pivoted the way I want it to be.
Can please someone help me out with this one. I welcome any solution be it a full lengthy query or a procedure.