попробуйте CTE:
;WITH FirstQ AS
(
SELECT 'Body' AS LineType, ItemName, Quantity FROM TableX
), SecondQ AS
(
SELECT 'Body' AS LineType, ItemName, Quantity FROM TableY
)
SELECT * FROM FirstQ
UNION ALL SELECT * FROM SecondQ
UNION ALL
SELECT 'Trailer' AS LineType, null As ItemName, ((SELECT COUNT(*) FROM FirstQ) +(SELECT COUNT(*) FROM SecondQ)) AS Quantity
Рабочий код образца:
declare @TableX table (ItemName varchar(5), Quantity int)
INSERT @TableX VALUES ('aa',10)
INSERT @TableX VALUES ('bb',20)
declare @TableY table (ItemName varchar(5), Quantity int)
INSERT @TableX VALUES ('cc',30)
;WITH FirstQ AS
(
SELECT 'Body' AS LineType, ItemName, Quantity FROM @TableX
), SecondQ AS
(
SELECT 'Body' AS LineType, ItemName, Quantity FROM @TableY
)
SELECT * FROM FirstQ
UNION ALL SELECT * FROM SecondQ
UNION ALL
SELECT 'Trailer' AS LineType, null As ItemName, ((SELECT COUNT(*) FROM FirstQ) +(SELECT COUNT(*) FROM SecondQ)) AS Quantity
ВЫХОД:
LineType ItemName Quantity
-------- -------- -----------
Body aa 10
Body bb 20
Body cc 30
Trailer NULL 3
(4 row(s) affected)