我有3张表如下:
表1包含以下内容
Id Name Section Salary
---------------------------------
1 Mark It 1000
2 Dad Hr 2000
表2包含此样本数据:
Id Item Salary
--------------------------
1 Holday 50
1 Food 30
1 Rent 100
2 Food 200
2 Rent 200
表3包含此数据:
Id Descriptions Cost
---------------------------
1 Bonce 150
1 Rate 300
2 Car 100
2 Bonce 15
2 Rate 30
我需要获得附加截图的数据:
答案 0 :(得分:0)
这是一个有趣的计算问题,与您的使用无关。它不是一个简单的连接表。这是SQL Server强制执行的一部分,您需要在报表工具中进行调整。
表格准备
DECLARE @table1 table (Id int, Name varchar(10), Section varchar(10), Salary decimal(18,2))
DECLARE @table2 table (Id int, Item varchar(10), Salary decimal(18,2))
DECLARE @table3 table (Id int, Descriptions varchar(10), Cost decimal(18,2))
INSERT @table1 values
(1, 'Mark', 'It', 1000)
,(2, 'Dad ', 'Hr', 2000)
INSERT @table2 Values
(1,'Holday', 50)
,(1,'Food ', 30)
,(1,'Rent ',100)
,(2,'Food ',200)
,(2,'Rent ',200)
INSERT @table3 values
(1, 'Bonce', 150)
,(1, 'Rate ', 300)
,(2, 'Car ', 100)
,(2, 'Bonce', 15)
,(2, 'Rate ', 30)
选择
;WITH
lv0(n) AS (SELECT 0 FROM (VALUES (0), (0))G(n)), --2
lv1(n) AS (SELECT 0 FROM lv0 a CROSS JOIN lv0 b), -- 4
lv2(n) AS (SELECT 0 FROM lv1 a CROSS JOIN lv1 b), -- 16
lv3(n) AS (SELECT 0 FROM lv2 a CROSS JOIN lv2 b), -- 256
lv4(n) AS (SELECT 0 FROM lv3 a CROSS JOIN lv3 b), -- 65,536
--lv5(N) as (select 0 from lv4 a cross join lv4 b), -- 4,294,967,296
tally(n) AS (SELECT Row_number() OVER( ORDER BY (SELECT NULL)) FROM lv4),
t1 AS (SELECT Row_number() OVER( ORDER BY id ) N ,* FROM @table1),
t2 AS (SELECT Row_number() OVER( ORDER BY id ) N ,* FROM @table2),
t3 AS (SELECT Row_number() OVER( ORDER BY id ) N ,* FROM @table3)
SELECT a.NAME
,a.section
,a.section
,b.item
,b.salary
,c.descriptions
,c.cost
,a.id
,b.id
,c.id
FROM tally t
CROSS JOIN t1 a
LEFT JOIN t2 b
ON t.n = b.n
AND a.id = b.id
LEFT JOIN t3 c
ON t.n = C.n
AND a.id = c.id
WHERE a.id IS NOT NULL
AND ( b.id IS NOT NULL
OR c.id IS NOT NULL )
ORDER BY a.n
,b.n
,c.n
结果
NAME section section item salary descriptions cost id id id
---------- ---------- ---------- ---------- --------------------------------------- ------------ --------------------------------------- ----------- ----------- -----------
Mark It It Holday 50.00 Bonce 150.00 1 1 1
Mark It It Food 30.00 Rate 300.00 1 1 1
Mark It It Rent 100.00 NULL NULL 1 1 NULL
Dad Hr Hr NULL NULL Car 100.00 2 NULL 2
Dad Hr Hr Food 200.00 Bonce 15.00 2 2 2
Dad Hr Hr Rent 200.00 Rate 30.00 2 2 2