1

有没有办法计算 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

4 回答 4

3

它应该是

SELECT fieldB, COUNT(DISTINCT  fieldA, fieldB) AS count 
FROM table 
GROUP BY fieldB;
于 2012-07-20T10:15:08.860 回答
0
SELECT   fieldA, COUNT(fieldB) AS count from
(SELECT DISTINCT fieldA, fieldB FROM table)a
FROM a GROUP BY a.fieldB
于 2012-07-20T10:16:54.157 回答
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

于 2012-07-20T10:20:01.970 回答
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
于 2012-07-20T10:20:03.847 回答