如何从具有相似列名的不同无关表中获取列?

时间:2019-03-29 12:07:52

标签: sql sql-server

我有3张桌子:

付款组:

PayGroupId   Name       Description    Code
1            US Weekly  US Weekly      USW
2            Can Weekly Canada Weekly  CANW
3            US Monthly US Monthly     USM
4            Can Monthly Can Monthly   CANM

付款方式:

PayTypeId   Name       Description    Code
1           Hourly     Hourly         H
2           Salary     Salaried       S

支付代码:

PayCodeId   Name       Description    Code
1           Regular    Regular        REG
2           PTO        PTO            PTO
3           Sick       Sick           SICK

我需要以下格式的报告:

PayGroup    PayType    PayCode
US Weekly   Hourly     Regular
Can Weekly  Salary     PTO        
US Monthly             Sick

我们可以这样做吗?

2 个答案:

答案 0 :(得分:5)

可疑,这可以为您带来想要的结果,但似乎很奇怪:

WITH PG AS(
    SELECT [Name],
           ROW_NUMBER() OVER (ORDER BY PayGroupID ASC) AS RN
    FROM PayGroup),
PT AS(
    SELECT [Name],
           ROW_NUMBER() OVER (ORDER BY PayTypeID ASC) AS RN
    FROM PayGroup),
PC AS(
    SELECT [Name],
           ROW_NUMBER() OVER (ORDER BY PayCodeID ASC) AS RN
    FROM PayCode)
SELECT PG.[Name] AS PayGroup,
       PT.[Name] AS PayType,
       PC.[Name] AS PayCode
FROM PG
     FULL OUTER JOIN PT ON PG.RN = PT.RN
     FULL OUTER JOIN PC ON PG.RN = PC.RN
                        OR PT.RN = PC.RN;

答案 1 :(得分:1)

CREATE TABLE #table1
    ([PayGroupId] int, [Name] varchar(11), [Description] varchar(13), [Code] varchar(4))
;

INSERT INTO #table1
    ([PayGroupId], [Name], [Description], [Code])
VALUES
    (1, 'US Weekly', 'US Weekly', 'USW'),
    (2, 'Can Weekly', 'Canada Weekly', 'CANW'),
    (3, 'US Monthly', 'US Monthly', 'USM'),
    (4, 'Can Monthly', 'Can Monthly', 'CANM')
;


CREATE TABLE #table2
    ([PayTypeId] int, [Name] varchar(6), [Description] varchar(8), [Code] varchar(1))
;

INSERT INTO #table2
    ([PayTypeId], [Name], [Description], [Code])
VALUES
    (1, 'Hourly', 'Hourly', 'H'),
    (2, 'Salary', 'Salaried', 'S')
;




CREATE TABLE #table3
    ([PayCodeId] int, [Name] varchar(7), [Description] varchar(7), [Code] varchar(4))
;

INSERT INTO #table3
    ([PayCodeId], [Name], [Description], [Code])
VALUES
    (1, 'Regular', 'Regular', 'REG'),
    (2, 'PTO', 'PTO', 'PTO'),
    (3, 'Sick', 'Sick', 'SICK')
;
select a.name PayGroup ,isnull(B.Name,'') PayType ,isnull(C.Name,'')PayCode
 from #table1 A left join #table2 B on a.[PayGroupId]=b.[PayTypeId]left join
 #table3 c on c.[PayCodeId]=a.[PayGroupId]


PayGroup    PayType PayCode
US Weekly   Hourly  Regular
Can Weekly  Salary  PTO
US Monthly          Sick
Can Monthly