使用COUNT()函数的SQL查询问题 [英] problem with SQL query using COUNT() function

查看:84
本文介绍了使用COUNT()函数的SQL查询问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下SQL查询:



I have the following SQL query:

SELECT DISTINCT `c1` FROM `table1` AS Column1 INNER JOIN `table2` ON `table1`.`c2`=`table2`.`c2`





以上查询从`table1`返回一些不同的行。 />
现在对于上面查询返回的每一行(c1列的值),我想计算`table2`中的行,其中`c1`列的值等于上面的查询返回值。例如,对于上面查询返回的单行,我有一个返回值'A'。



现在这行的单个查询将是这样的:





Above query returns some distinct rows from `table1`.
Now for each row(value of c1 column) returned by the above query, I want to count the rows from `table2` which have column `c1` value equal to to the above query returned value. for example, for a single row returned by the above query, I have a returned value 'A'.

Now the single query for this row would be something like this:

SELECT COUNT(*) FROM `table2` WHERE `table2`.`c1` = A





现在,作为SQL的新手,我的问题是,如何在一个查询中混合上述两个查询。

以某种方式,例如,在最终(混合)查询返回的行中,我有一个列返回'A'值,另一列返回`table2`的行数,列'c1`值为'A'?



我希望我已经清楚地解释了我的问题。



任何有关此问题的帮助都将受到高度赞赏。



提前谢谢。



Now, being new to SQL, my question is, How can I mix both of the above queries in one single query.
In a way that,for example, in a row returned by the final(mixed) query,I have a column returning 'A' value and another column returning the number of rows of `table2` having column `c1` with value of 'A'?

I hope I have explained my question clearly.

Any help with this problem would be highly appreciated.

Thanks in advance.

推荐答案

我觉得这就是你的船尾呃



I think this is what you are after

select
t1.Column1 
,count(*) 'Count'
from
TableA t1
inner join
TableB t2
on
t1.Column1 = t2.Column1
group by
t1.Column1


希望这样做:

Hope this will do:
SELECT COUNT(table2.C2) FROM table2
INNER JOIN table1 ON table2.C2= table1.C2
GROUP BY table2.C2
WHERE table2.c1 = A





此外,请查看以下链接以获取更详细的查询:

http://stackoverflow.com/questions/17751393/sql-query-with-join-count-and -where [ ^ ]



谢谢。



Further, have a look on below link for more detailed queries:
http://stackoverflow.com/questions/17751393/sql-query-with-join-count-and-where[^]

Thanks.


这篇关于使用COUNT()函数的SQL查询问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆