mysql - sql语句中有多个where子句?
问题描述
我有一个简单的sessions
表格,如下所示:
sid watchtime
1 01:07:00
2 01:07:00
3 01:34:00
4 01:36:00
5 01:36:00
6 01:59:00
7 01:59:00
8 00:00:00
9 00:00:00
10 03:42:00
11 00:16:00
12 00:49:00
13 00:55:00
14 00:00:00
15 00:05:00
16 00:05:00
现在,我想显示 watchtime>=5
和 watchtime的计数<5
。我尝试了以下解决方案:
SELECT count(watchtime) as lessthan_five FROM sessions
WHERE watchtime <=5
AND count(watchtime) as morethan_five
from sessions WHERE watchtime >5";
我收到以下错误:
1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 1 行的 'as morethanfive from sessions where WHERE watchtime >=5"' 附近使用
我在我的代码中做错了什么?
解决方案
您可以使用条件聚合来获得所需的结果,利用 MySQL 在数字上下文中将布尔值视为 1 或 0:
SELECT SUM(watchtime <= '00:05:00') AS lessthan_five,
SUM(watchtime > '00:05:00') AS morethan_five
FROM sessions
输出:
lessthan_five morethan_five
5 11
推荐阅读
- python - Return predictions wav2vec fairseq
- c# - .NET Core API 中的 CQS - DI 配置不起作用
- java - How to see lines drawn in real time. Java Swing
- javascript - 如何将多个元素添加到数组中
- kotlin - Moshi 工厂在从 json 字符串反序列化时忽略空值并使用 kotlin 默认值
- if-statement - 如何动态连接表单结果
- javascript - How to call an external Javascript function in a dynamic action?
- sql - Oracle 在子查询中按列分组
- java - Spring Boot caching with ContentVersionStrategy prohibits resource compression with gzip
- php - Create all combinations of array with keys