SQL来计算所需表的不同计数

SQL来计算所需表的不同计数,sql,sql-server,tsql,Sql,Sql Server,Tsql,这是我的表,我需要找到表中不同计数的总数。 我需要考虑ID1和ID2来找到唯一的计数。 因此,计数结果应根据状态分组。考虑上面的例子 id1 id2 year State Gender ==== ====== ====== ===== ======= 1 A 2008 ca M 1 B 2008 ca M 3 A 2009 ny F

这是我的表,我需要找到表中不同计数的总数。 我需要考虑ID1和ID2来找到唯一的计数。 因此,计数结果应根据状态分组。考虑上面的例子

id1     id2    year State Gender    
====  ====== ====== ===== =======    
1       A      2008    ca      M    
1       B      2008    ca      M    
3       A      2009    ny      F   
3       A      2008    ny      F     
4       A      2009    tx      F
我提出的问题是:

i need to get the result as
ca - count : 2  and for ny it should be : 1 as  3 A is repeated twice.
在这个查询中,我无法计算id1、id2的不同计数。 我应该如何修改查询以获得所需的结果。
任何帮助都将不胜感激

如果您使用的是sql server 2005或更高版本,则可以使用排名函数。比如说,

select state,gender,year,count(distinct id1,id2) from table1 
group by state,gender,year
另一种crud方法是将id1和id2组合起来,并利用这种组合

WITH temp AS(
    SELECT
        state,gender,[year],
        rank() OVER (ORDER BY id1,id2) AS rank1
    FROM table1
)
SELECT
    state,gender,[year],
    COUNT(DISTINCT rank1)
FROM 
    temp
GROUP BY state,gender, [year]

尝试使用子选择:

select
    state, gender, [year],
    count (distinct(cast(id1 as varchar(10)) + id2))
from
    try1
group by state, gender, [year]

我不是专家,但我搞定了这个,这似乎有效

select state, gender, year,
    count(select count(*) as total from table1
          where state = t.state and gender = t.gender and year = t.year
          group by id1, id2)
    from table1 t
group by state, gender, year

我很高兴接受批评。我是来学习的

[更新]

请尝试以下操作:

select count(1) from stack where state='ny' group by id1, id2;
select @@ROWCOUNT;

您需要选择哪些列?
select state, count(distinct cast(id1 as varchar) + id2) cnt from table1 
group by state
SELECT [state],
  (SELECT COUNT(*) FROM (
    SELECT DISTINCT id1, id2 FROM table1 WHERE [state] = t.[state]
  ) z) AS cnt
FROM table1 t
GROUP BY [state]