如何编写一个sql查询来获取这个?

时间:2018-01-02 04:50:21

标签: mysql sql sql-server

我有两张桌子。我希望得到理想的结果。

表1

id | salary

01 | 500

04 | 300

07 | 700

表2

id | salary

02 | 300

05 | 800

06 | 700

我想输出

id | salary

01 | 500

02 | 300

03 | <em>null</em>

04 | 300

05 | 800

06 | 700

07 | 700

08 | <em>null</em>

09 | <em>null</em>

10 | <em>null</em>

3 个答案:

答案 0 :(得分:2)

如果您使用 SQL Server ,那么此解决方案可能适合您

;WITH CTE
AS(
    SELECT
        ID = 1

    UNION ALL

    SELECT
        Id = Id+1
        FROM CTE
            WHERE Id <  10
),C2
AS
(
    SELECT
        ID,
        Salary
        FROM YourTable1

    UNION ALL

    SELECT
        ID,
        Salary
        FROM YourTable2
)
SELECT
    CTE.ID,
    C2.Salary
    FROM CTE
        LEFT JOIN C2
            ON CTE.ID = C2.ID

答案 1 :(得分:0)

这是一个替代解决方案,我使用数字表并创建零填充的数字(最好使用SQL pad zeros function

实际上,存储薪资数据的两个表是相同的,您只需要一个UNION或UNION ALL 下面的选择模拟了一个类似于UNION案例的解决方案,但是如果每个表上都有两个条目,那么ID号就像&#39; 01&#39;然后只使用第一个表薪水。请根据您的情况考虑这样的情况。

SELECT
    RIGHT(REPLICATE('0',2) + Convert(varchar(2),Number),2) as id,
    coalesce(t1.salary,t2.salary) as salary
FROM master..spt_values num
LEFT JOIN [Table 1] as t1 on t1.id = RIGHT(REPLICATE('0',2) + Convert(varchar(2),num.Number),2)
LEFT JOIN [Table 2] as t2 on t2.id = RIGHT(REPLICATE('0',2) + Convert(varchar(2),num.Number),2)
WHERE 
    Type = 'P' and Number <= 10
ORDER BY Number

答案 2 :(得分:0)

对于SQL Server ...这应该有帮助。您可以用您需要生成的最大数量替换20。

;WITH SingleDigits(Number) AS
(
    SELECT Number
    FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8),
    (9), (0)) AS X(Number)
)
,Series AS
(
    SELECT (d1.Number+1) + (10*d2.Number) + (100*d3.Number) + (1000*d4.Number) Number
    from
    SingleDigits as d1,
    SingleDigits as d2,
    SingleDigits as d3,
    SingleDigits as d4
)
,CTE1 AS ( SELECT id, salary FROM Table1 UNION ALL SELECT id, Salary from table2 )
SELECT s.Number Id, c.salary FROM Series s 
LEFT JOIN  CTE1 c ON s.Number = c.Id
WHERE Number < 20