SQL - 计算包含两个不同字段的行数

时间:2012-07-20 10:13:31

标签: mysql database

有没有办法获得fieldB的计数,但只有fieldA和fieldB组合是唯一的?

例如

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 count FROM table GROUP BY fieldB'。这似乎返回了fieldB中所有值的计数,而不仅仅是具有唯一fieldA的值。

我希望我想做的事情有道理,我发现很难说出来。我正在尝试用SQL做什么?

由于

4 个答案:

答案 0 :(得分:3)

应该是

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

答案 1 :(得分:0)

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

答案 2 :(得分: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 A 1 B 1 C

答案 3 :(得分: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