2012-07-20 46 views
1

是否有任何獲取fieldB計數的方法,但只有fieldA和fieldB組合是唯一的?SQL - 計算包含兩個不同字段的行數

例如

fieldA  fieldB 
X   A 
X   B 
Y   C 
X   B 
Y   A 

場B的計數將返回:

A = 2 
B = 1 
C = 1 

我一直在使用 'SELECT DISTINCT FIELDA,COUNT(fieldB)AS數量FROM表GROUP BY fieldB' 嘗試。這似乎返回fieldB中所有值的計數,而不僅僅是具有唯一fieldA的值。

我希望我想要做的事情有意義,我很難說出來。我試圖用SQL來做什麼?

感謝

回答

3

應該

SELECT fieldB, COUNT(DISTINCT fieldA, fieldB) AS count 
FROM table 
GROUP BY fieldB; 
+0

感謝所有的快速回答,這只是我嘗試過的第一個,並且似乎完美地工作。 - 謝謝 – jd182 2012-07-20 10:30:43

0
SELECT fieldA, COUNT(fieldB) AS count from 
(SELECT DISTINCT fieldA, fieldB FROM table)a 
FROM a GROUP BY a.fieldB 
0

我覺得這讓你有

Declare @mytbl table (fieldA char(1), fieldB char(1)) 
insert into @mytbl 
select 'X','A' 
union all select 'X','B' 
union all select 'Y','C' 
union all select 'X','B' 
union all select 'Y','A' 

select COUNT(*), LEFT(myfields,1) 
from 
(
select distinct fieldb + fielda as myfields 
from @mytbl 
group by fieldb + fielda 
) a 
group by LEFT(myfields,1) 

返回

2一 1B中 1 C

0
DECLARE @mytb table 
(
fieldA varchar(10), 
fieldB varchar(10) 
); 

INSERT into @mytb values('X','A'); 
INSERT into @mytb values('X','B'); 
INSERT into @mytb values('Y','C'); 
INSERT into @mytb values('X','B'); 
INSERT into @mytb values('Y','A'); 

SELECT fieldB,count(DISTINCT fieldA+fieldB) as count 
from @mytb 
group BY fieldB; 


    fieldB  count 
---------- ----------- 
    A   2 
    B   1 
    C   1 
+0

@RaphaëlAlthaus對不起,但它返回2爲A. – 2012-07-20 10:38:18

+0

Downvote? @RaphaëlAlthaushttp://sqlfiddle.com/#!3/61853/1 – 2012-07-20 10:41:27

+1

Sql Server。嘗試與MySQL ... http://sqlfiddle.com/#!2/61853/1 – 2012-07-20 10:43:47

相關問題