J,
Я видел вышеупомянутое решение , и оно также действительно, но вы также можете попробовать использовать PIVOT .Я создал демо для вас, пожалуйста, проверьте это решение, которое также может помочь вам.
ДЕМО
ОБЪЯВИТЬ СТОЛЫ И ВСТАВИТЬ ЗАПИСИ
DECLARE @Table2016 AS TABLE ( Item VARCHAR(50), Price FLOAT, Quantity INT );
DECLARE @Table2017 AS TABLE ( Item VARCHAR(50), Price FLOAT, Quantity INT );
DECLARE @Table2018 AS TABLE ( Item VARCHAR(50), Price FLOAT, Quantity INT );
DECLARE @Table2019 AS TABLE ( Item VARCHAR(50), Price FLOAT, Quantity INT );
INSERT INTO @Table2016 (Item,Price,Quantity) VALUES
('Shoe' ,20,10),
('Shoe' ,30,15),
('Cups' ,10,30),
('Towels',30,20),
('Towels',25,20),
('Towels',20,20)
INSERT INTO @Table2017 (Item,Price,Quantity) VALUES
('Shoe' ,40,30),
('Shoe' ,50,20),
('Towels',30,30),
('Towels',20,30)
INSERT INTO @Table2018 (Item,Price,Quantity) VALUES
('Shoe' ,20,10),
('Cups' ,10,30),
('Towels',30,20),
('Towels',25,20),
('Towels',20,20)
INSERT INTO @Table2019 (Item,Price,Quantity) VALUES
('Shoe' ,20,10),
('Shoe' ,30,15),
('Cups' ,10,30),
('Towels',30,20),
('Towels',25,20),
('Towels',20,20)
УДАЛИТЬ ВСЕ ТАБЛИЦЫ И ВСТАВИТЬ В ТАБЛИЦУ ТЕМП.
SELECT Item,Price,Quantity,PriceYear,QuantityYear INTO TempFinal
FROM (
SELECT Item,Price,Quantity, 'Price2016' as PriceYear,'Quantity2016' as QuantityYear FROM @Table2016
UNION ALL
SELECT Item,Price,Quantity, 'Price2017' as PriceYear,'Quantity2017' as QuantityYear FROM @Table2017
UNION ALL
SELECT Item,Price,Quantity, 'Price2018' as PriceYear,'Quantity2018' as QuantityYear FROM @Table2018
UNION ALL
SELECT Item,Price,Quantity, 'Price2019' as PriceYear,'Quantity2019' as QuantityYear FROM @Table2019
) MyTables
ЗАПРОС БЕЗ ГРУППЫ
SELECT item, [Price2016],[Quantity2016],[Price2017],[Quantity2017],[Price2018],[Quantity2018],[Price2019],[Quantity2019]
FROM (
SELECT item,Price,Quantity,PriceYear,QuantityYear
FROM TempFinal) up
PIVOT (SUM(Quantity) FOR QuantityYear IN ([Quantity2016],[Quantity2017],[Quantity2018],[Quantity2019])) AS pvt
PIVOT (SUM(Price) FOR PriceYear IN ([Price2016],[Price2017],[Price2018],[Price2019])) AS pvt2
ORDER BY item
ЗАПРОС С GROUPBY
SELECT item, SUM([Price2016])[Price2016],SUM([Quantity2016])[Quantity2016],SUM([Price2017])[Price2017],SUM([Quantity2017])[Quantity2017],SUM([Price2018])[Price2018],SUM([Quantity2018])[Quantity2018],SUM([Price2019])[Price2019],SUM([Quantity2019])[Quantity2019]
FROM (
SELECT item,Price,Quantity,PriceYear,QuantityYear
FROM TempFinal) up
PIVOT (SUM(Quantity) FOR QuantityYear IN ([Quantity2016],[Quantity2017],[Quantity2018],[Quantity2019])) AS pvt
PIVOT (SUM(Price) FOR PriceYear IN ([Price2016],[Price2017],[Price2018],[Price2019])) AS pvt2
GROUP by item
ORDER BY item
ТАБЛИЦА СНИЖЕНИЯ ТЕМПЕРАТУРЫ
DROP TABLE TempFinal