枢轴和左连接

时间:2019-07-11 05:42:11

标签: sql sql-server tsql pivot left-join

T-SQL,在透视时需要在列中组合两个值的帮助。

我有一个Employee表,其中包含以下数据-

EmpId   Status  L#
E1      A       1
E1      B       1
E2      A       2
E2      B       2
E3      B       3
E3      C       3
E3      D       3

和主管表-

EmpId   Sup
E1      S1
E2      S2
E3      S3

当状态为B或C时,我想合并L#的值

EmpId   Sup   A   B,C   D
E1      S1    1   1     0
E2      S2    1   2     0
E3      S3    0   2     1

3 个答案:

答案 0 :(得分:0)

这可能会帮助

DECLARE @TableEmp TABLE (EmpId VARCHAR(10),   Status VARCHAR(10),  L# INT)
INSERT INTO @TableEmp VALUES
('E1',  'A',   1    ),
('E1',  'B',   1    ),
('E2',  'A',   2    ),
('E2',  'B',   2    ),
('E3',  'B',   3    ),
('E3',  'C',   3    ),
('E3',  'D',   3    )


DECLARE @TableSup TABLE(EmpId VARCHAR(10),  Sup VARCHAR(10))
INSERT INTO @TableSup VALUES
('E1',  'S1'),
('E2',  'S2'),
('E3',  'S3')

SELECT EmpId, Sup ,ISNULL(A,0) A, ISNULL(B,0) B,ISNULL(C,0) C,ISNULL(D,0) D
FROM(
    SELECT e.EmpId, Sup,Status,ISNULL(L#,0) L#
    FROM @TableEmp e
    LEFT JOIN @TableSup s ON e.EmpId = s.EmpId
) p
PIVOT(
  SUM(L#)
  FOR Status IN (A, B, C,D)
) piv

enter image description here

答案 1 :(得分:0)

以下查询应执行您想要的操作:

CREATE TABLE #emp (EmpID VARCHAR(10), [Status] VARCHAR(10), L# INT)
CREATE TABLE #sup (EmpID VARCHAR(10), [Sup] VARCHAR(10))
INSERT INTO #emp VALUES
('E1','A',0),
('E1','B',1), 
('E2','A',2),
('E2','B',2),
('E3','B',3),
('E3','C',5),
('E3','D',5)
INSERT INTO #sup VALUES
('E1','S1'),
('E2','S2'),
('E3','S3')

SELECT * FROM (
SELECT e.EmpID, s.Sup, t.[Status], COUNT(L#) AS [Cnt]
FROM #emp e
INNER JOIN #sup s ON e.EmpID = s.EmpID
CROSS APPLY (VALUES(CASE WHEN e.[Status] IN ('B','C') THEN 'B,C' ELSE e.[Status] END)) AS T([Status])
GROUP BY e.EmpID, s.Sup, t.[Status] ) A
PIVOT (MAX([Cnt]) FOR [Status] IN ([A],[B,C],[D])) pvt

结果如下,

EmpID   Sup   A     B,C   D
E1      S1    1     1     NULL
E2      S2    1     1     NULL
E3      S3    NULL  2     1

答案 2 :(得分:0)

仅使用条件聚合。我不清楚结果如何。以下计数状态:

select s.empid, s.sup,
       sum(case when status = 'A' then 1 else 0 end) as a,
       sum(case when status in ('B', 'C') then 1 else 0 end) as bc,
       sum(case when status = 'D' then 1 else 0 end) as d
from employee e join
     supervisor s
     on e.empid = s.empid
group by s.empid, s.sup;