在单个查询中添加多个 where 子句

时间:2020-12-22 10:24:47

标签: mysql sql node.js

我想从 Node.js 运行 SQL 查询。我想显示 4 个季度中每个季度具有特定状态的项目总数。

这是我的两个季度的代码:

SELECT
SUM(CurrentStatus = 'On Hold') onHold_Q1,
SUM(CurrentStatus = 'In Progress') inProgress_Q1,
SUM(CurrentStatus = 'Not Started') notStarted_Q1,
SUM(CurrentStatus = 'Completed') completed_Q1,
SUM(CurrentStatus = 'Routine Activity') routineActivity_Q1,
SUM(CurrentStatus = 'Done But Not Published') doneButNotPublished_Q1
FROM office.officedata
WHERE Quarter = 'Q1';

SELECT
SUM(CurrentStatus = 'On Hold') onHold_Q2,
SUM(CurrentStatus = 'In Progress') inProgress_Q2,
SUM(CurrentStatus = 'Not Started') notStarted_Q2,
SUM(CurrentStatus = 'Completed') completed_Q2,
SUM(CurrentStatus = 'Routine Activity') routineActivity_Q2,
SUM(CurrentStatus = 'Done But Not Published') doneButNotPublished_Q2
FROM office.officedata
WHERE Quarter = 'Q2'; 

我想将上述两个查询合并为一个查询。因为,我要从后端 (Node.js) 运行此查询,所以我希望在一个请求中一次性获得所有季度的数据。我不想向 mySQL 发送多个请求。我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以按季度分组:

SELECT Quarter,
    SUM(CurrentStatus = 'On Hold') onHold,
    SUM(CurrentStatus = 'In Progress') inProgress,
    SUM(CurrentStatus = 'Not Started') notStarted,
    SUM(CurrentStatus = 'Completed') completed,
    SUM(CurrentStatus = 'Routine Activity') routineActivity,
    SUM(CurrentStatus = 'Done But Not Published') doneButNotPublished
FROM office.officedata
WHERE Quarter in ('Q1', 'Q2')
GROUP BY Quarter;

这每季度生成一行,值以列为单位。虽然可以将所有内容都放在同一行(输入更多内容!),但我发现这个结果更有用。

答案 1 :(得分:0)

您想使用 vs code error file

SELECT
SUM(CurrentStatus = 'On Hold') onHold,
SUM(CurrentStatus = 'In Progress') inProgress,
SUM(CurrentStatus = 'Not Started') notStarted,
SUM(CurrentStatus = 'Completed') completed,
SUM(CurrentStatus = 'Routine Activity') routineActivity,
SUM(CurrentStatus = 'Done But Not Published') doneButNotPublished
FROM office.officedata
WHERE Quarter = 'Q1'
UNION SELECT
SUM(CurrentStatus = 'On Hold') onHold,
SUM(CurrentStatus = 'In Progress') inProgress,
SUM(CurrentStatus = 'Not Started') notStarted,
SUM(CurrentStatus = 'Completed') completed,
SUM(CurrentStatus = 'Routine Activity') routineActivity,
SUM(CurrentStatus = 'Done But Not Published') doneButNotPublished
FROM office.officedata
WHERE Quarter = 'Q2'; 
相关问题