У меня есть данные, как показано ниже
CREATE TABLE #TEMP(OrderId int, Country varchar(100),Area varchar(100),Hotel varchar(100),CountryDetail varchar(100),AreaDetail varchar(100),HotelDetail varchar(100))
INSERT INTO #TEMP
VALUES(1,'Bhutan','Thimphu','Taj Tashi','Bhutan country info','Thimphu area info','Taj Tashi hotel info'),
(2,'Bhutan','Punakha','COMO Uma Punakha','Bhutan country info','Punakha area info','COMO Uma Punakha hotel info'),
(3,'Bhutan','Punakha','COMO Uma Paro','Bhutan country info','Punakha area info','COMO Uma Paro hotel info')
Ожидаемый результат Я получаю после
Item ItemDetail OrderId
Bhutan Bhutan country info 1
Thimphu Thimphu area info 1
Taj Tashi Taj Tashi hotel info 1
Punakha Punakha area info 2
COMO Uma Punakha COMO Uma Punakha hotel info 2
COMO Uma Paro COMO Uma Paro hotel info 3
Вывод основан на не дублировании страны, района или отеля и отображается только один раз согласно orderid
Пробовал до сих пор
;WITH CTE AS (SELECT OrderId,Country,Area,Hotel,CountryDetail,AreaDetail,HotelDetail,
CountryDupe = ROW_NUMBER() OVER (PARTITION BY Country ORDER BY OrderId),
AreaDupe = ROW_NUMBER() OVER (PARTITION BY Area ORDER BY OrderId),
HotelDupe = ROW_NUMBER() OVER (PARTITION BY Hotel ORDER BY OrderId)
from #TEMP)
SELECT ITEM, OrderId
FROM (SELECT OrderId,CountryDetail,
CASE WHEN CountryDupe=1 THEN Country ELSE '' END AS Country,
CASE WHEN AreaDupe = 1 THEN Area ELSE '' END AS Area,
CASE WHEN HotelDupe = 1 THEN Hotel ELSE '' END AS Hotel
FROM CTE) P
UNPIVOT(
ITEM
FOR ITEMS IN (Country,Area,Hotel)
) UNPVT
WHERE LEN(ITEM)>1
ORDER BY OrderId
Не уверен, как вытащить подробности связанных элементов здесь.
SQL FIDDLE здесь