Пример схемы с данными, как показано ниже
CREATE Table tab1
(
ID INT IDENTITY,
[DATE] DATE,
Userid INT
)
GO
CREATE Table tab2
(
ID INT IDENTITY,
StoreName varchar(20)
)
GO
CREATE Table tab3
(
tab3ID INT IDENTITY,
OpenTime varchar(10),
CLoseTime varchar(10),
Table1_fk INT,
Table2_fk INT
)
GO
ALTER Table tab1 ADD CONSTRAINT Pk_Table1 PRIMARY KEY (Id)
ALTER Table tab2 ADD CONSTRAINT Pk_Table2 PRIMARY KEY (Id)
ALTER Table tab3 ADD CONSTRAINT Fk_tab3Table2 FOREIGN KEY (Table1_fk) REFERENCES tab1 (Id)
ALTER Table tab3 ADD CONSTRAINT Fk_tab3Table1 FOREIGN KEY (Table2_fk) REFERENCES tab2 (Id)
GO
INSERT INTO tab1
SELECT '01-02-2019',20 UNION ALL
SELECT '01-02-2019',20 UNION ALL
SELECT '03-25-2019',20 UNION ALL
SELECT '03-25-2019',20
GO
INSERT INTO tab2
SELECT 'ShoesShop' UNION ALL
SELECT 'CoputerSalesShop'
GO
INSERT INTO tab3
SELECT '10:00 Am','05:00 Pm',1,1 UNION ALL
SELECT '09:00 Am','04:00 Pm',2,2 UNION ALL
SELECT '10:00 Am','05:00 Pm',3,1 UNION ALL
SELECT '10:00 Am','04:00 Pm',4,2
Я написал некоторый код, который почти соответствует вашему требованию, используя динамический sql. Я думаю, это поможет вам
IF OBJECT_ID('dbo.TempTable') IS NOT NULL
DROP TABLE TempTable
SELECT ID,
StoreName,
[Times],
[TimeData] ,
Dates INTO TempTable
FROM
(
SELECT StoreName,
OpenTime,
CLoseTime,
[DATE] AS Dates,
t1.ID
FROM tab3 t3
INNER JOIN tab2 t2
ON t2.ID = t3.Table2_fk
INNER JOIN tab1 t1
ON t1.ID = t3.Table1_fk
)AS A
CROSS APPLY ( VALUES (OpenTime,'OpenTime'),
(CLoseTime,'CLoseTime')
)AS dt([Times],[TimeData] )
SELECT * FROM TempTable
DECLARE @Sql nvarchar(max),
@DynamicColumn nvarchar(max),
@MaxDynamicColumn nvarchar(max)
SELECT @DynamicColumn = STUFF((SELECT DISTINCT', '+QUOTENAME(CAST(Dates AS VARCHAR(10)))
FROM TempTable FOR XML PATH ('')),1,1,'')
SELECT @MaxDynamicColumn = STUFF((SELECT DISTINCT', '+'MAX('+QUOTENAME(CAST(Dates AS VARCHAR(10)))+') AS '+QUOTENAME(CAST(Dates AS VARCHAR(10)))
FROM TempTable FOR XML PATH ('')),1,1,'')
SET @Sql='SELECT StoreName,'+ @MaxDynamicColumn+'
FROM
(
SELECT *,STUFF((SELECT '' AND ''+ [TimeData] +'' : ''+ [Times]
FROM TempTable i WHERE i.id = o.id FOR XML PATH ('''')),1,4,'''') AS ShopDateTIme
FROM TempTable o
)AS src
PIVOT
(
MAX(ShopDateTIme) FOR [Dates] IN ('+@DynamicColumn+')
) AS Pvt
GROUP BY StoreName '
EXEC (@Sql)
PRINT @Sql