/* Works In Microsoft SQL Server */
CREATE TABLE #VehicleTypes
(
VehTypID BIGINT ,
Name NVARCHAR(MAX)
);
INSERT INTO #VehicleTypes
SELECT *
FROM (
SELECT 1 AS bbbb ,
'Car' AS aaaa
UNION ALL
SELECT 2 AS bbbb ,
'Public Bus' AS aaaa
UNION ALL
SELECT 3 AS bbbb ,
'Ambulance' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Trucks' AS aaaa
UNION ALL
SELECT 5 AS bbbb ,
'Auto' AS aaaa
) AS a;
CREATE TABLE #Services
(
VehTypID BIGINT ,
Name NVARCHAR(MAX)
);
INSERT INTO #Services
SELECT *
FROM (
SELECT 1 AS bbbb ,
'Towing Alert' AS aaaa
UNION ALL
SELECT 1 AS bbbb ,
'Over Speed Alert' AS aaaa
UNION ALL
SELECT 3 AS bbbb ,
'Location' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Odo Meter' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Speed Limit' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Fuel Limit' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'SOS' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Emergency CONTROL' AS aaaa
) AS a;
CREATE TABLE #NotificationAndReports
(
VehTypID BIGINT ,
Name NVARCHAR(MAX)
);
INSERT INTO #NotificationAndReports
SELECT *
FROM (
SELECT 1 AS bbbb ,
'Popup' AS aaaa
UNION ALL
SELECT 1 AS bbbb ,
'Email' AS aaaa
UNION ALL
SELECT 1 AS bbbb ,
'SMS' AS aaaa
UNION ALL
SELECT 1 AS bbbb ,
'WhatsApp' AS aaaa
UNION ALL
SELECT 2 AS bbbb ,
'Digital Status' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Email Reports' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Daily Summary Reports' AS aaaa
UNION ALL
SELECT 4 AS bbbb ,
'Live Tracking' AS aaaa
) AS a;
/*Way 1 */
SELECT CASE WHEN LAG(#VehicleTypes.Name, 1, 0) OVER ( ORDER BY #VehicleTypes.VehTypID ) = '0'
OR LAG(#VehicleTypes.Name, 1, 0) OVER ( ORDER BY #VehicleTypes.VehTypID ) <> #VehicleTypes.Name THEN
#VehicleTypes.Name
ELSE NULL
END AS VehicleName ,
CASE WHEN LAG(#Services.Name, 1, 0) OVER ( ORDER BY #VehicleTypes.VehTypID ) = '0'
OR LAG(#Services.Name, 1, 0) OVER ( ORDER BY #VehicleTypes.VehTypID ) <> #Services.Name THEN
#Services.Name
ELSE NULL
END AS ServicesName ,
#VehicleTypes.VehTypID ,
#Services.VehTypID ,
#NotificationAndReports.VehTypID ,
#NotificationAndReports.Name
FROM #VehicleTypes
RIGHT JOIN #Services ON #Services.VehTypID = #VehicleTypes.VehTypID
LEFT JOIN #NotificationAndReports ON #NotificationAndReports.VehTypID = #VehicleTypes.VehTypID;
/*Way 2 */
SELECT CASE WHEN ROW_NUMBER() OVER ( PARTITION BY #VehicleTypes.Name
ORDER BY #VehicleTypes.VehTypID
) = 1 THEN #VehicleTypes.Name
ELSE NULL
END AS VehicleName ,
CASE WHEN ROW_NUMBER() OVER ( PARTITION BY #Services.Name
ORDER BY #VehicleTypes.VehTypID
) = 1 THEN #Services.Name
ELSE NULL
END AS ServicesName ,
#VehicleTypes.VehTypID ,
#Services.VehTypID ,
#NotificationAndReports.VehTypID ,
#NotificationAndReports.Name
FROM #VehicleTypes
RIGHT JOIN #Services ON #Services.VehTypID = #VehicleTypes.VehTypID
LEFT JOIN #NotificationAndReports ON #NotificationAndReports.VehTypID = #VehicleTypes.VehTypID;
DROP TABLE #VehicleTypes ,
#NotificationAndReports ,
#Services;