在Sql Server 2008中合并两个枢轴

时间:2013-09-12 08:35:51

标签: sql-server

现在我使用两个枢轴来显示结果。请帮助我合并这些支点。我希望结果像EmpId,Daystatus的分解以及各个EmpId的[1]的数量。

DayStatus字段具有'P','PH'和& 'A'和IsLate字段具有'1'和& '0'。

要分解EmpId和DayStatus

SELECT *
FROM (
SELECT EmpId, DayStatus
FROM Attendance
WHERE _Date >= '08/01/2013' AND _Date <= '08/31/2013' 
) m
PIVOT (
COUNT(DayStatus)
FOR DayStatus IN ([P], [PH], [A])
) n

Output is:
EmpId   P   PH  A
EC2818  5   3   0
EC2825  8   0   0
EC2826  7   0   1
EC2827  4   2   2
EC2828  6   2   0
EC2829  8   0   0
EC2830  5   3   0
EC2831  6   1   1
EC2833  7   0   1
EC2834  6   1   1

获得EmpId和IsLate的分手

SELECT *
FROM (
SELECT EmpId, IsLate
FROM Attendance
WHERE _Date >= '08/01/2013' AND _Date <= '08/31/2013' 
) m
PIVOT (
COUNT(IsLate)
FOR IsLate IN ([1])
) n

Output is:
EmpId   IsLate
EC2818  0
EC2825  0
EC2826  0
EC2827  1
EC2828  0
EC2829  1
EC2830  0
EC2831  0
EC2833  0
EC2834  2

现在我想要输出如下:

Desired Output:
EmpId   P   PH  A   IsLate
EC2818  5   3   0   0
EC2825  8   0   0   0
EC2826  7   0   1   0
EC2827  4   2   2   1
EC2828  6   2   0   0
EC2829  8   0   0   1
EC2830  5   3   0   0
EC2831  6   1   1   0
EC2833  7   0   1   0
EC2834  6   1   1   2

请帮帮我。

2 个答案:

答案 0 :(得分:0)

加入他们:

select  *
from    (
        ... pivot1 query ...
        ) q1
full outer join
        (
        ... pivot2 query ...
        ) q2
pm      q1.EmpId = q2.EmpId

答案 1 :(得分:0)

尝试下面的内容,它应该将两个数据透视表的结果连接在一起:

SELECT EMP.*, LATE.IsLate
FROM (
    SELECT *
    FROM (
        SELECT EmpId, DayStatus
        FROM Attendance
        WHERE _Date >= '08/01/2013' AND _Date <= '08/31/2013' 
    ) m
    PIVOT (
        COUNT(DayStatus)
        FOR DayStatus IN ([P], [PH], [A])
    ) ) EMP
JOIN 
    (SELECT *
    FROM (
        SELECT EmpId, IsLate
        FROM Attendance
        WHERE _Date >= '08/01/2013' AND _Date <= '08/31/2013' 
    ) m
    PIVOT (
        COUNT(IsLate)
        FOR IsLate IN ([1])
    ) n ) LATE
ON EMP.EmpId = LATE.EmpId