Sql查询所需的帮助

时间:2010-01-20 10:26:26

标签: sql sql-server tsql

我有问题,有三张桌子

Table A 

ID        Employee    
1         1    
2         2
3         3


Table B
Id        EMployee        HoursWorked         HoursCode
1          1                 10               Basic Hours
2          1                 20               Holiday Pay
3          2                 10               Basic hours
4          2                 15               OverTime

Table C 
ID        Employee         Payments            PayCode
1           1                 100              Bonus
2           2                 150              Bonus
3           2                 250              Student Loan

我想用最小的行从这些表中取出记录,所以我可以有一行说

id        Employee          Hour               HoursCode       Payments      PayCode
1          1                 10                Basic Hours     100           Bonus     
2          1                 20                Holiday Pay      null         null
3          2                 10                basic hours      150          Bonus 
4          2                 15                 OverTime        250          Student loan

我花了很多时间试图得到它...但是在第二行没有获得Null它在员工1的第二行中获得100个奖金

我可以这样做吗请帮助

1 个答案:

答案 0 :(得分:3)

WITH    bn AS
        (
        SELECT  *, ROW_NUMBER() OVER (PARTITION BY employee ORDER BY id) AS rn
        FROM    b
        ),
        cn AS
        (
        SELECT  *, ROW_NUMBER() OVER (PARTITION BY employee ORDER BY id) AS rn
        FROM    c
        )
SELECT  *
FROM    bn
FULL JOIN
        cn
ON      bn.employee = cn.employee
        AND bn.rn = cn.rn
ORDER BY
        COALESCE(bn.employee, cn.employee), COALESCE(bn.rn, cn.rn)