我有两张表table1
和table2
。 table1
列id
和table2_id
,而table2
有id
和category
。我需要根据table1
中包含值table2.category
或Regular
的两个单独值来计算来自Special
的行。
我在两个查询中完成了这个,但我想知道是否可以在单个sql中完成。我的疑问是:
"SELECT COUNT(t1.id) AS regular FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = t2.id WHERE t2.category = 'Regular'";
"SELECT COUNT(t1.id) AS special FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = pr.id WHERE t2.category = 'Special'";
感谢。
修改
第二个查询JOIN应该是ON t1.t2_id = t2.id
而不是ON t1.t2_id = pr.id
。很抱歉可能造成的混乱。请相应地更新/编辑您的答案/评论。
答案 0 :(得分:3)
将Where
条件移至CASE
语句并执行计数
以下是使用Conditional Aggregate
SELECT
COUNT(case when t2.category = 'Regular' then t1.id end) AS Regular,
COUNT(case when t2.category = 'Special' then t1.id end) AS special
FROM table1 t1
INNER JOIN table2 t2 ON t1.t2_id = pr.id
Where t2.category IN ('Regular','Special' )
注意:我已将LEFT JOIN
更改为INNER JOIN
,因为您只想在table2.category
为'Regular'
或{{1}时进行计数所以不要在这里使用'Special'
答案 1 :(得分:0)
而不是
"SELECT COUNT(t1.id) AS regular FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = t2.id WHERE t2.category = 'Regular'";
"SELECT COUNT(t1.id) AS special FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.t2_id = pr.id WHERE t2.category = 'Special'";
你可以这样做:
select t2.category, count(t1.id)
from table1 t1
left outer join table2
on t1.t2_id = t2.id
group by t2.category
having t2.category in ('Regular', 'Special')
建议的查询对已连接的记录进行分组,过滤组并选择类别名称及其计数。