查询有多个计数

时间:2014-09-02 10:57:53

标签: sql sql-server tsql aggregate-functions

DECLARE @temp TABLE
(SEQ_NBR INT, TERR_CD NVARCHAR(20), DSTR_CD NVARCHAR(20), RGN_CD NVARCHAR(20), AREA_CD NVARCHAR(20), CNTR_CD NVARCHAR(20))

INSERT INTO @temp VALUES (1, 'TERR A', 'DSTR A', 'RGN A', 'AREA A', 'BUS CNTR A')
INSERT INTO @temp VALUES (1, 'TERR B', 'DSTR A', 'RGN A', 'AREA A', 'BUS CNTR A')
INSERT INTO @temp VALUES (1, 'TERR C', 'DSTR B', 'RGN A', 'AREA A', 'BUS CNTR A')
INSERT INTO @temp VALUES (1, 'TERR A2', 'DSTR A2', 'RGN A2', 'AREA A2', 'BUS CNTR A2')
INSERT INTO @temp VALUES (1, 'TERR B2', 'DSTR B2', 'RGN A2', 'AREA A2', 'BUS CNTR A2')
INSERT INTO @temp VALUES (2, 'TERR C', 'DSTR B', 'RGN A', 'AREA A', 'BUS CNTR A')
INSERT INTO @temp VALUES (2, 'TERR D', 'DSTR C', 'RGN B', 'AREA A', 'BUS CNTR A')
INSERT INTO @temp VALUES (2, 'TERR B2', 'DSTR B2', 'RGN A2', 'AREA A2', 'BUS CNTR A2')

SELECT * FROM @temp

现在,我需要这样的输出:

SEQ_NBR TERR_NM TERR_CNT    DSTR_NM DSTR_CNT    RGN_CD  RGN_CNT AREA_CD AREA_CNT    CTR_CD  CTR_CNT
1   TERR A  1       DSTR A  2       RGN A   3   AREA A  3       BUS CNTR A  3
1   TERR B  1       DSTR A  2       RGN A   3   AREA A  3       BUS CNTR A  3
1   TERR C  1       DSTR B  1       RGN A   3   AREA A  3       BUS CNTR A  3
1   TERR A2 1       DSTR A2 1       RGN A2  2   AREA A2 2       BUS CNTR A2 2
1   TERR B2 1       DSTR B2 1       RGN A2  2   AREA A2 2       BUS CNTR A2 2
2   TERR C  1       DSTR B  1       RGN A   1   AREA A  2       BUS CNTR A  2
2   TERR D  1       DSTR C  1       RNG B   1   AREA A  2       BUS CNTR A  2
2   TERR B2 1       DSTR B2 1       RGN A2  1   AREA A2 1       BUS CNTR A2 1

这里,SEQ_NBR 1与5个差分TERR_CD相关联,因此TERR_CNT为1. TERR_CD“A”和“B”属于DSTR_CD A而TERR_CD“C”属于DSTR_CD B,因此DSTR的计数为2 DSTR B为A和1.对于RGN_CD“A”,计数为3。

有人可以帮我查询吗?

1 个答案:

答案 0 :(得分:1)

这很简单:

SELECT 
  SEQ_NBR, 
  TERR_CD, 
  COUNT(*) over (PARTITION BY TERR_CD, SEQ_NBR) TERR_CNT,
  DSTR_CD,
  COUNT(*) over (PARTITION BY DSTR_CD, SEQ_NBR) DSTR_CNT,
  RGN_CD, 
  COUNT(*) over (PARTITION BY RGN_CD, SEQ_NBR) RGN_CNT,
  AREA_CD, 
  COUNT(*) over (PARTITION BY AREA_CD, SEQ_NBR) AREA_CNT,
  CNTR_CD,
  COUNT(*) over (PARTITION BY CNTR_CD, SEQ_NBR) CNTR_CNT
FROM @temp