0

需要有关查询的小帮助。例如,以下是我的两张数据表

declare @table1 table (id int, column1 int)
declare @table2 table (id int, column2 int, column3 int)

insert into @table1 (id, column1) values (1, 10)
insert into @table1 (id, column1) values (2, 20)
insert into @table1 (id, column1) values (3, 30)

insert into @table2 (id, column2, column3) values (1, 100, 8)
insert into @table2 (id, column2, column3) values (1, 200, 7)
insert into @table2 (id, column2, column3) values (1, 300, 6)
insert into @table2 (id, column2, column3) values (1, 300, 5)
insert into @table2 (id, column2, column3) values (2, 400, 4)
insert into @table2 (id, column2, column3) values (2, 500, 3)
insert into @table2 (id, column2, column3) values (3, 600, 2)
insert into @table2 (id, column2, column3) values (3, 700, 1)

--select * from @table1
--select * from @table2

-- Query 1
select t1.id, count(*) RecCount from @table1 t1 join (select distinct id, column2 from @table2) t2
on t1.id = t2.id
group by t1.id

-- Query 2
select t1.id, count(*) RecCount from @table1 t1 join @table2 t2
on t1.id = t2.id
group by t1.id

根据上述查询,我​​可以得到以下输出

id  RecCount
 1   3
 2   2
 3   2

从上面的查询中,查询 2 不会返回预期的输出,请告诉我我的查询 1 是否会返回正确的输出。请让我知道在派生查询中使用 distinct 是否合适。

4

1 回答 1

0

您在表 2 中有 4 条 ID 为 1 的记录。为什么您希望计数为 3?

如果要计算每列 column2 中不同值的数量,请执行

select t1.id, count(distinct column2) RecCount 
from @table1 t1 join @table2 t2
on t1.id = t2.id
group by t1.id

尽管在这种情况下,连接不是必需的,并且

select id, count(distinct column2) RecCount 
from @table2 
group by id

就足够了。

于 2013-09-24T08:55:49.097 回答