SELECT查询同一个表中的两个变量

时间:2015-12-19 11:15:48

标签: sql database sqlite

我问你怎么能在SQL中模仿这个逻辑:

SELECT var1, var2 FROM table1,WHERE var1 = COUNT(table1.status == 1) AND var2 = COUNT(table2.status == 2)

我希望在var1中存储status = 1条目数和var2status = 2条目数SELECT

4 个答案:

答案 0 :(得分:3)

您可以将COUNTCASE结合使用:

SELECT 
   COUNT(CASE WHEN t1.Status = 1 THEN 1 END) AS var1,
   COUNT(CASE WHEN t1.Status = 2 THEN 1 END) AS var2
FROM table1 t1;

或者,您可以使用SUM

SELECT 
   SUM(t1.status = 1) AS var1,
   SUM(t1.status = 2) AS var2
FROM table1 t1;

答案 1 :(得分:2)

如果您的表很大且在status列上有索引,则需要能够使用索引来快速执行(两个索引查找比一个表扫描更快),这需要使用WHERE过滤行。

如果您可以将结果作为两行处理,请使用compound query

SELECT count(*) FROM Table1 WHERE status = 1
UNION ALL
SELECT count(*) FROM Table1 WHERE status = 2;

如果您需要两列结果,可以使用子查询:

SELECT (SELECT count(*) FROM Table1 WHERE status = 1) AS var1,
       (SELECT count(*) FROM Table1 WHERE status = 2) AS var2;

答案 2 :(得分:1)

如果要在一行中的两个变量中设置两个结果差,则可以使用此选项。

SELECT 
   @var1 = t1.column,
   @var2 = t2.column
FROM table1 t1 INNER JOIN table1 t2 ON 
       a.column = 'value' AND 
       b.column = 'value2';

答案 3 :(得分:0)

使用子查询,使用sql的count()方法获取计数

所以,

SELECT var1, var2 FROM table1 WHERE var1 = (SELECT count(*) from table 1 where table1.status == 1) AND var2 = (SELECT count(*) from table 1 where table1.status == 2)