下應該做的伎倆......
IF OBJECT_ID('tempdb..#Vehicle', 'U') IS NOT NULL
DROP TABLE #Vehicle;
GO
CREATE TABLE #Vehicle (
VehicleID INT NOT NULL PRIMARY KEY CLUSTERED,
VehicleName VARCHAR(10) NOT NULL
);
GO
INSERT #Vehicle (VehicleID, VehicleName) VALUES
(1, 'Car1'), (2, 'Car2'), (3, 'Car3');
GO
IF OBJECT_ID('tempdb..#Orders', 'U') IS NOT NULL
DROP TABLE #Orders;
GO
CREATE TABLE #Orders (
OrderID INT NOT NULL PRIMARY KEY CLUSTERED,
ClientName VARCHAR(15) NOT NULL,
PhoneNumber VARCHAR(10) NOT NULL,
ServiceDate DATETIME NOT NULL,
VehicleID INT NOT NULL -- create FK refference back to Vehicle.VehicleID)
);
GO
-- create an index to support the row_number() function...
-- The sort cost is greater than the difference between a seek & scan...
CREATE NONCLUSTERED INDEX ix_Orders_VehicleID_ServiceDate
ON #Orders (VehicleID, ServiceDate)
INCLUDE (ClientName, PhoneNumber);
GO
INSERT #Orders (OrderID, ClientName, PhoneNumber, ServiceDate, VehicleID) VALUES
(1, ' Jack ', '11111', '07-22-2017 10:22:00 AM', 2),
(2, ' Susan', '22222', '07-22-2017 01:30:00 PM', 2),
(3, ' Hany ', '33333', '07-22-2017 10:22:00 AM', 3),
(4, ' Karim', '44444', '07-21-2017 08:22:00 AM', 1),
(5, ' Halaa', '55555', '07-22-2017 05:22:00 PM', 3);
GO
--SELECT * FROM #Vehicle v;
--SELECT * FROM #Orders o;
--=======================================================================
DECLARE @WorkDate DATE = '2017-07-22';
WITH
cte_AddRN AS (
SELECT
o.OrderID, o.ClientName, o.PhoneNumber, o.ServiceDate, o.VehicleID,
RN = ROW_NUMBER() OVER (PARTITION BY o.VehicleID ORDER BY o.ServiceDate)
FROM
#Orders o
WHERE
CAST(o.ServiceDate AS DATE) = @WorkDate
)
SELECT
VehicleName = MAX(v.VehicleName),
Order1 = MAX(CASE WHEN ar.RN = 1 THEN ar.ClientName + ' (' + ar.PhoneNumber + ')' ELSE '' END),
Order2 = MAX(CASE WHEN ar.RN = 2 THEN ar.ClientName + ' (' + ar.PhoneNumber + ')' ELSE '' END),
Order3 = MAX(CASE WHEN ar.RN = 3 THEN ar.ClientName + ' (' + ar.PhoneNumber + ')' ELSE '' END),
Order4 = MAX(CASE WHEN ar.RN = 4 THEN ar.ClientName + ' (' + ar.PhoneNumber + ')' ELSE '' END),
Order5 = MAX(CASE WHEN ar.RN = 5 THEN ar.ClientName + ' (' + ar.PhoneNumber + ')' ELSE '' END)
FROM
#Vehicle v
LEFT JOIN cte_AddRN ar
ON v.VehicleID = ar.VehicleID
GROUP BY
v.VehicleID;
結果...
VehicleName Order1 Order2 Order3 Order4 Order5
----------- --------------- --------------- --------------- --------------- ---------------
Car1
Car2 Jack (11111) Susan (22222)
Car3 Hany (33333) Halaa (55555)
這樣做的一個相當標準的方法是使用['STUFF FOR XML PATH('')'](https://stackoverflow.com/search?q=STUFF+FOR+XML+PATH) – ZLK