T / SQL中的组计数

时间:2015-06-15 22:14:46

标签: sql sql-server sql-server-2012

来源:

CREATE TABLE #TempTab (Value INT, Value1 varchar(10), Value2 varchar(10), 
GRP varchar(10))
INSERT INTO #TempTab
SELECT 1,'One','One','One'
UNION ALL
SELECT 1,'One','One','One'
UNION ALL
sELECT 1,'One','One','Two'
UNION ALL
SELECT 2,'One','One','One'
UNION ALL
SELECT 2,'One','One','Two'
UNION ALL
SELECT 2,'One','One','Three'
UNION ALL
SELECT 3,'One','One','One'
UNION ALL
SELECT 3,'One','One','One'

当前查询工作:

SELECT Value, Value1, Value2, GRP
, COUNT(1) OVER(PARTITION BY Value, Value1, Value2) CNT 
, ROW_NUMBER() OVER(PARTITION BY Value, Value1, Value2, GRP ORDER BY Value) RN
, CASE
            WHEN COUNT(*) OVER (PARTITION BY Value, Value1, Value2, GRP) > 1 THEN 1
            ELSE 0
         END IsMultiple
FROM #TempTab


DROP TABLE #TempTab

当前输出:

Value   Value1  Value2  GRP     CNT RN  IsMultiple
1       One     One     One     3   1   1
1       One     One     One     3   2   1
1       One     One     Two     3   1   0
2       One     One     One     3   1   0
2       One     One     Two     3   1   0
2       One     One     Three   3   1   0
3       One     One     One     2   1   1
3       One     One     One     2   2   1

期望的输出:

Value   Value1  Value2  GRP     CNT RN  IsMultiple  NoUniqueGRPed
1       One     One     One     3   1   1           2
1       One     One     One     3   2   1           2
1       One     One     Two     3   1   0           2
2       One     One     One     3   1   0           3
2       One     One     Two     3   1   0           3
2       One     One     Three   3   1   0           3
3       One     One     One     2   1   1           1
3       One     One     One     2   2   1           1

目标:

我正在尝试派生一个名为NoUniqueGRPed的字段。这个领域是  基本上是基于Value,Value1和。的唯一分组记录的计数  Value2字段。即,值= 1,值1 = 1,值2 = 1  三个记录,但两个独特的GRP值(一和二)所以NoUniqueGRPed  应该是2。

我在试图弄清楚如何做到这一点时遇到了麻烦  聚集/分组。

2 个答案:

答案 0 :(得分:2)

您可以尝试qith cross apply

SELECT ...,
       ca.NoUniqueGRPed
FROM #TempTab t1
CROSS APPLY(SELECT COUNT(DISTINCT GRP) AS NoUniqueGRPed 
            FROM #TempTab t2 
            WHERE t1.Value = t2.Value)ca

答案 1 :(得分:2)

您可以直接使用窗口函数执行此操作:

select tt.*,
       count(distinct grp) over (partition by value, value1, value2) as NewColumn
from #TempTab tt

编辑:

我虽然已经修复了这个限制。唉。您可以使用sum()row_number()

的组合来完成此操作
select tt.*,
       sum(case when seqnum = 1 then 1 else 0 end) over (partition by value, value1, value2) as NewColumn
from (select tt.*, row_number() over (partition by value, value1, value2, grp order by grp) as seqnum
      from #TempTab tt
     ) tt