DECLARE @D1 DateTime DECLARE @D2 DateTime SET @D1 = '2017-10-01' SET @D2 = '2017-10-02' SELECT * FROM (SELECT *,1 As j FROM YourTable WHERE YourColumn = @D1) As A LEFT OUTER JOIN (SELECT *,1 As j FROM YourTable WHERE YourColumn = @D2) As B ON A.j = B.j
กรณี 3 ตาราง
DECLARE @D1 DateTime DECLARE @D2 DateTime SET @D1 = '2017-10-01' SET @D2 = '2017-10-02' SELECT * FROM (SELECT *,1 As j FROM YourTable1 WHERE YourColumn = @D1) As A LEFT OUTER JOIN (SELECT *,1 As j FROM YourTable2 WHERE YourColumn = @D2) As B ON A.j = B.j LEFT OUTER JOIN (SELECT *,1 As j FROM YourTable3 WHERE YourColumn = @D2) As C ON A.j = C.j
กรณีนี้ ใช้ INNER JOIN แทน LEFT OUTER JOIN ได้ผลลัพธ์เหมือนกัน
ReplyDeleteกรณี join 3 ตาราง
ReplyDeleteDECLARE @D1 DateTime
SET @Date = '2017-10-02'
SELECT *
FROM (SELECT *,1 As j FROM [SPP18MW] WHERE [date_in] = @Date) As A
LEFT OUTER JOIN
(SELECT *,1 As j FROM TG WHERE [date_in] = @Date) As B
ON A.j = B.j
LEFT OUTER JOIN
(SELECT *,1 As j FROM TG4 WHERE [date_in] = @Date) As C
ON A.j = C.j