I've been reading a few articles and just can't get a grasp of SQL. I have this SQL query:
SELECT C.customer_ID, C.l_Name AS Surname,
C.f_Name AS 'First Name', C.travel_Date,
T.tour_Name,
S.f_Name AS Staff, S.l_Name AS Staff_Surname
FROM Customers AS C
LEFT JOIN Tour AS T ON C.tour_ID = T.tour_ID
LEFT JOIN Staff_Day AS SD ON C.tour_ID = SD.tour_ID
LEFT JOIN Staff AS S ON SD.staff_ID = S.staff_ID
LEFT JOIN Staff_Day AS SD_2 ON SD_2.sd_Date = C.travel_Date
WHERE C.travel_Date >= '2014-07-08 00:00:00'
AND C.travel_Date <= '2014-07-08 23:59:59'
AND SD.sd_Date >= '2014-07-08 00:00:00'
AND SD.sd_Date <= '2014-07-08 23:59:59'
AND C.customer_ID NOT IN (SELECT O.customer_ID
FROM Customers AS C, Orders AS O
WHERE C.travel_Date >= '2014-07-08 00:00:00'
AND C.travel_Date <= '2014-07-08 23:59:59' AND C.customer_ID = O.customer_ID )
Which returns 4 results:
6176 Lau Elton 2014-07-08 09:07:33 Thriller Jo(Boat)
6176 Lau Elton 2014-07-08 09:07:33 Thriller Gosta (the boss man)
6192 minc yvonne 2014-07-08 09:07:47 Thunderstruck Jo(Jetty)
6192 minc yvonne 2014-07-08 09:07:47 Thunderstruck Meri (Jetty)
I'm really stumped as to how to merge the 4 results into 2. If it helps, each customer (Lau, Minc) have 2 staff members, which I believe is the cause for the 2 extra returned results. I have attempted a GROUP_CONCAT but I don't understand it enough to get it working. I'd like the results to be like so:
6176 Lau Elton 2014-07-08 09:07:33 Thriller Jo(Boat), Gosta (the boss man)
6192 minc yvonne 2014-07-08 09:07:47 Thunderstruck Jo(Jetty), Meri (Jetty)
Is this at all possible? Apologies if this is a duplicate already.
Thanks to @Michael Haugen for pointing me in the right direction, I was able to modify my existing SQL query to return the expected results:
SELECT C.customer_ID, C.l_Name AS Surname,
C.f_Name AS 'First Name', C.travel_Date,
T.tour_Name,
GROUP_CONCAT(S.f_Name, S.l_Name ) AS Staff_Concat
FROM Customers AS C
LEFT JOIN Tour AS T ON C.tour_ID = T.tour_ID
LEFT JOIN Staff_Day AS SD ON C.tour_ID = SD.tour_ID
LEFT JOIN Staff AS S ON SD.staff_ID = S.staff_ID
LEFT JOIN Staff_Day AS SD_2 ON SD_2.sd_Date = C.travel_Date
WHERE C.travel_Date >= '2014-07-08 00:00:00'
AND C.travel_Date <= '2014-07-08 23:59:59'
AND SD.sd_Date >= '2014-07-08 00:00:00'
AND SD.sd_Date <= '2014-07-08 23:59:59'
AND C.customer_ID NOT IN (SELECT O.customer_ID
FROM Customers AS C, Orders AS O
WHERE C.travel_Date >= '2014-07-08 00:00:00'
AND C.travel_Date <= '2014-07-08 23:59:59' AND C.customer_ID = O.customer_ID )
GROUP BY C.customer_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.