简体   繁体   English

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

[英]Adding multiple where clauses in a single query

I want to run an SQL query from the Node.js.我想从 Node.js 运行 SQL 查询。 I want to show the total number of projects that have specific status in each of the 4 quarters.我想显示四个季度中每个季度具有特定状态的项目总数。

Here's my code for the 2 quarters:这是我的 2 个季度的代码:

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'; 

I want to join the above two queries into a single query.我想将上述两个查询合并为一个查询。 Since, I am going to run this query from the backend (Node.js), I want the data for the quarters all at once in a single request.因为,我要从后端 (Node.js) 运行这个查询,所以我希望在一个请求中一次获得所有季度的数据。 I don't want to send multiple request to mySQL.我不想向 mySQL 发送多个请求。 How can I do that?我怎样才能做到这一点?

You can group by quarter:您可以按季度分组:

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;

This generates one row per quarter, with the values in columns.这将每季度生成一行,列中的值。 While it would be possible to put everything on the same row (with more typing,).虽然可以将所有内容放在同一行(输入更多)。 I find that this result is more useful.我发现这个结果更有用。

You want to use the UNION clause您想使用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 = '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'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM