我在SQL中有100个Column表,但我想一次为每个列的频率,是否可以在SQL中?

时间:2016-02-10 09:31:02

标签: sql-server

EMPNO   ENAME   JOB      MGR    ------------------
7369    SMITH   CLERK    7902   
7499    ALLEN   SALESMAN 7698   
7499    SMITH   SALESMAN 7698   
7369    JONES   MANAGER  7839

我需要像这样出来

Empno cnt ENAME  cnt ------------ Same out put remaining columns also
7369  2   SMITH  2
7499  2   ALLEN  1
      JONES  1

2 个答案:

答案 0 :(得分:1)

可能是您应该查看此解决方案,因为它为发布的输出提供了确切的答案,但我们需要解决动态解决方案

DECLARE @Table1 TABLE 
    (MPNO int, ENAME varchar(5), JOB varchar(8), MGR int)
;

INSERT INTO @Table1
    (MPNO, ENAME, JOB, MGR)
VALUES
    (7369, 'SMITH', 'CLERK', 7902),
    (7499, 'ALLEN', 'SALESMAN', 7698),
    (7499, 'SMITH', 'SALESMAN', 7698),
    (7369, 'JONES', 'MANAGER', 7839)
;


select T.MPNO, T.cnt, TT.ENAME,TT.cnt,TTT.JOB,TTT.cnt,TTTT.MGR,TTTT.cnt
from (select g.MPNO,count(MPNO)cnt, row_number() over (order by MPNO) as seqnum
      from @Table1 g
      GROUP BY g.MPNO
     ) T full outer join
     (select g.ENAME, count(ENAME)cnt,row_number() over (order by ENAME) as seqnum
      from @Table1 g
      GROUP BY g.ENAME
     ) TT
     on T.seqnum = TT.seqnum
     full outer join 
     (select g.JOB, count(JOB)cnt,row_number() over (order by JOB) as seqnum
      from @Table1 g
      GROUP BY g.JOB)TTT
      on TT.seqnum = TTT.seqnum
       full outer join 
     (select g.MGR, count(MGR)cnt,row_number() over (order by MGR) as seqnum
      from @Table1 g
      GROUP BY g.MGR)TTTT
      on TTTT.seqnum = TTT.seqnum
     ;

答案 1 :(得分:1)

SELECT A.EMPNO, A.CNT, B.ENAME,B.CNT,C.JOB,C.CNT,D.MGR,D.CNT
FROM (SELECT G.EMPNO,COUNT(EMPNO)CNT, ROW_NUMBER() OVER (ORDER BY EMPNO) AS NUMBER
      FROM #TABLE G
      GROUP BY G.EMPNO
     ) A FULL OUTER JOIN
     (SELECT G.ENAME, COUNT(ENAME)CNT,ROW_NUMBER() OVER (ORDER BY ENAME) AS NUMBER
      FROM #TABLE G
      GROUP BY G.ENAME
     ) B
     ON A.NUMBER = B.NUMBER
    LEFT JOIN 
     (SELECT G.JOB, COUNT(JOB)CNT,ROW_NUMBER() OVER (ORDER BY JOB) AS NUMBER
      FROM #TABLE G
      GROUP BY G.JOB)C
      ON B.NUMBER = C.NUMBER
      LEFT JOIN 
     (SELECT G.MGR, COUNT(MGR)CNT,ROW_NUMBER() OVER (ORDER BY MGR) AS NUMBER
      FROM #TABLE G
      GROUP BY G.MGR)D
      ON D.NUMBER = C.NUMBER