在Subquery中再次过滤

时间:2016-03-28 13:03:03

标签: mysql sql

有没有办法再次过滤子查询中的选定项?

例如:我已经从公司过滤了用户:

SELECT * FROM user WHERE companyId = 123

现在我想过滤一下今年从上面公司创建的女性,男性和用户。目前我使用此查询:

SELECT 
  (SELECT COUNT(id) FROM user WHERE companyId = 123 && sex = "male") maleUser,
  (SELECT COUNT(id) FROM user WHERE companyId = 123 && sex = "female") femaleUser,
  (SELECT COUNT(id) FROM user WHERE companyId = 123 && YEAR(created) = YEAR(NOW())) currentYearUser

但我想让它变得更容易:

SELECT 
  (SELECT COUNT(id) FROM userAlreadyFilteredByCompany WHERE sex = "male") maleUser,
  (SELECT COUNT(id) FROM userAlreadyFilteredByCompany WHERE sex = "female") femaleUser,
  (SELECT COUNT(id) FROM userAlreadyFilteredByCompany WHERE YEAR(created) = YEAR(NOW())) currentYearUser

FROM
  (SELECT id, created FROM user WHERE companyId = 123) userAlreadyFilteredByCompany

有办法做到这一点吗?我认为在选择已经过滤的结果时,它更容易理解并且工作量更低。

3 个答案:

答案 0 :(得分:1)

SELECT 
  SUM(CASE WHEN sex = "male" THEN 1 ELSE 0 END) as maleUser,
  SUM(CASE WHEN sex = "female" THEN 1 ELSE 0 END) as femaleUser,
  SUM(CASE WHEN YEAR(created) = YEAR(NOW()) THEN 1 ELSE 0 END) as currentYearUser

FROM user 
WHERE companyId = 123

您可以使用CASE / WHEN添加条件并将数字相加

答案 1 :(得分:0)

试试这个:

SELECT
    SUM(sex = "male") maleUser,
    SUM(sex = "female") femaleUser,
    SUM(YEAR(created) = YEAR(NOW())) currentYearUser
FROM user WHERE companyId = 123

答案 2 :(得分:0)

嘿,你可以这样试试:

import {Component} from 'angular2/core';
import {ComponentTwo} from 'angular2/core';

@Component({
    selector: 'app',
    template: `<h1>Title Here</h1>'
}),

@Component({
    selector: 'appTwo',
    template: `<h1>Another Title Here</h1>'
})
export class AppComponent { }