使用SQL在查询中的同一列上实现两个不同的操作
我是一个SQL初学者程序员,我想写一个SQL代码,它应该以两种不同的方式计算列中的条目数。就像第一次一样,只需计算它们,然后只计算那些大于5的值 我正在使用下面的代码,但它给出了错误使用SQL在查询中的同一列上实现两个不同的操作,sql,Sql,我是一个SQL初学者程序员,我想写一个SQL代码,它应该以两种不同的方式计算列中的条目数。就像第一次一样,只需计算它们,然后只计算那些大于5的值 我正在使用下面的代码,但它给出了错误 SELECT table1.col1, Count(table1.col1) AS Expr1, count (where(table1.col1)>5) as expr2 FROM table1 GROUP BY tabl1.col1 错误是关于在中使用的where表达式:coun
SELECT
table1.col1,
Count(table1.col1) AS Expr1,
count (where(table1.col1)>5) as expr2
FROM table1
GROUP BY tabl1.col1
错误是关于在中使用的where表达式:count(where(table1.col1)>5)作为expr2。
是否有其他sql函数可用于在计数前过滤出大于5的值
谢谢。您想要条件聚合:
SELECT table1.col1,
Count(table1.col1) AS Expr1,
SUM(case when table1.col1 > 5 then 1 else 0 end) as expr2
FROM table1
GROUP BY table1.col1;
某些版本的SQL将布尔值视为整数值0
和1
。对于这些,可以将表达式简化为:
SELECT t1.col1,
Count(t1.col1) AS Expr1,
SUM(t1.col1 > 5) as expr2
FROM table1 t1
GROUP BY t1.col1;
此版本还引入了表别名。这使查询更具可读性,并修复了orderby
子句中的打字错误
select
col1,
count(col1) as Expr1,
sum(case when col1 > 5 then 1 else 0 end) as expr2
from table1
group by col1
或
首先,只需为每个col1>5添加1即可。第二个是计算表达式的所有非空值,当col1>5时,则col1结束
,如果col1>5
否则等于null
,则等于col1
-
SELECT table1.col1,
SUM(case when table1.col1 > 5 then 1 else 0 end) as expr2,
Count(table1.col1) AS Expr1
FROM table1
GROUP BY tabl1.col1
你很接近:
SELECT
col1,
count(*) AS Expr1,
sum(case when col1)>5 then 1 end) as expr2
FROM table1
GROUP BY col1
将
SUM
与CASE…END
一起使用。非常感谢Gordon Linoff回答这个问题。我在MS Access查询SQL中尝试过这段代码(因为我现在没有任何其他SQL程序),但它不起作用。。这是给失踪操作员的错误。谢谢戈登,我已经解决了这个问题。现在我使用switch语句,而不是case,因为MS Access支持switch。。非常感谢你帮助我。。
SELECT
col1,
count(*) AS Expr1,
sum(case when col1)>5 then 1 end) as expr2
FROM table1
GROUP BY col1