在同一个表上具有不同 where 子句的两个选择查询 [英] two select queries with different where clause on same table

查看:44
本文介绍了在同一个表上具有不同 where 子句的两个选择查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表关注者和关注人数..

i have a table follower and following count..

想要在一个存储过程中获取两者的计数..是否可以在同一个表上有两个具有不同 where 条件的选择查询?

want to get the count of both in one stored procedure.. is it possible to have two select queries with different where condition on same table possible?

CREATE TABLE Table1
    ([val1] int, [val2] int, [val3] int, [val4] int, other int)
;

INSERT INTO Table1
    ([val1], [val2], [val3], [val4], other)
VALUES
    (1, 26, 13, 1, 1),
    (2, 13, 26, 1, 1),
(3, 10, 26, 1, 1),
(4, 26, 13, 1, 1),
(5, 14, 26, 1, 1)
;

我的选择查询

(select count(*) as following_count from table1 where val2=26)

(select count(*) as follower_count from table1 where val3=26)

SQL FIDDLE 链接

推荐答案

你可以这样做:

SELECT
    SUM(CASE WHEN val2=26 THEN 1 ELSE 0 END) AS following_count,
    SUM(CASE WHEN val3=26 THEN 1 ELSE 0 END) AS follower_count
FROM
    table1

这篇关于在同一个表上具有不同 where 子句的两个选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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