python - SQL Query, Getting Rid of Repeat Selects
问题描述
I'm using sqlite3 in python and I have a table that has the following columns:
recordid(int), username(text), locations(text), types(text), occupancy(int), time_added(datetime), token(text) and (undo).
I have the following query where I am selecting data from the table depending on what the occupancy is and the time added is between the 2 specified times the user inputs which is start_date and end_date:
('''SELECT locations, types,
(SELECT COUNT (occupancy) FROM traffic WHERE undo = 0 AND occupancy = 1 AND types = ? AND time_added BETWEEN ? AND ?),
(SELECT COUNT (occupancy) FROM traffic WHERE undo = 0 AND occupancy = 2 AND types = ? AND time_added BETWEEN ? AND ?),
(SELECT COUNT (occupancy) FROM traffic WHERE undo = 0 AND occupancy = 3 AND types = ? AND time_added BETWEEN ? AND ?),
(SELECT COUNT (occupancy) FROM traffic WHERE undo = 0 AND occupancy = 4 AND types = ? AND time_added BETWEEN ? AND ?),
FROM traffic WHERE types = ? GROUP BY type''',
(vehicle, start_date, end_date, vehicle, start_date, end_date, vehicle, start_date, end_date, vehicle, start_date, end_date, vehicle)
Is there anyway to condense this so I don't have to copy and paste the same thing multiple times just to change the occupancy? I tried using a for loop but that didn't really get me anywhere.
Cheers!
解决方案
我很确定可以大大简化查询:
SELECT type
SUM( occupancy = 1 ) as cnt_1,
SUM( occupancy = 2 ) as cnt_2,
SUM( occupancy = 3 ) as cnt_3,
SUM( occupancy = 4 ) as cnt_4
FROM traffic
WHERE undo = 0 AND
type = ? AND
time_added BETWEEN ? AND ?
GROUP BY type;
不过,我不确定这是否正是您的问题所在。
推荐阅读
- oauth-2.0 - 如何在 oAuth 2.0 中存储和使用访问令牌和刷新令牌以保持用户的登录状态?(吉拉 OAuth 2.0)
- python - Pandas DataFrame 基于依赖于具有累积计数规则的其他列的逻辑创建新列
- android - Android:如何从相机获取原始图像数据
- node.js - 将 pdf 转换为图像不适用于 Windows 上的 Nodejs sharp
- single-sign-on - 当我们在 MS Edge 中启用 IE 模式时,ADFS SSO 失败
- bash - zsh 和 bashrc 命令未找到 ts-node
- apache-spark - 检查每个 RDD spark 内部的数据
- stm32 - 如何使用 HAL_I2C_Transmit?
- javascript - 如何将可点击对象添加到 AFRAME 中的模型数组
- amazon-web-services - 找不到 ecs-deploy 命令