查找由SQL Server中的表中的另一列分区的一组列的不同数字

时间:2015-01-26 14:57:18

标签: sql sql-server sql-server-2008 windows-7

我正在使用Windows 7上的SQL Server 2008.

我需要找到由另一列分区的一组列的不同数量。

表:

ID  value1 value2 value3 
--------------------------
358 32169   31984  9716 
358 9441    94     97897
235 32169   31984  9716 
235 8464    8454   36197
235  8646   97     36879

结果:

ID   distinct_num_of_value1_value2_value3  
------------------------------------------
358            2      // 358 has two distinct rows with v1 v2 v3 
235            3      // 235 has 3 distinct rows with v1 v2 v3 

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

怎么样

select
    id,
    count(distinct cast(value1 as varchar(32)) + '_' + cast(value2 as varchar(32)) + '_' + cast(value3 as varchar(32))) as distinct_num_of_value1_value2_value3
from
    YourTable
group by
    ID

答案 1 :(得分:0)

测试表:

DECLARE @t table(ID int,  value1 int, value2 int, value3  int)
INSERT @t values
  (358,32169,31984,9716),(358,9441,94,97897),
  (235,32169,31984,9716),(235,8464,8454,36197),
  (235,8646,97,36879)

查询:

--use group by

;WITH CTE AS
(
  SELECT
    id, value1, value2, value3
   FROM
     @t
  GROUP BY 
    id, value1, value2, value3
)
SELECT 
  count(*) cnt, 
    id
FROM
  CTE
GROUP BY
  id

--or use distinct

;WITH CTE AS
(
  SELECT
    distinct id, value1, value2, value3
   FROM
     @t
)
SELECT 
  count(*) cnt, 
    id
FROM
  CTE
GROUP BY
  id

结果:

cnt id
3   235
2   358