MYSQL:根据if语句获取结果两次

时间:2015-10-28 00:37:56

标签: mysql if-statement count

我试图从部门表中获取每个部门,来自员工表的富人和穷人员工人数。 到目前为止,我能够得到其中一个,但似乎无法想象如何为每个部门分两行写入富人和穷人。

SELECT Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor'), 
COUNT(*)  FROM `Employees`, `Depts` 
WHERE Depts.Dept = Employees.Dept 
GROUP BY Depts.Department

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

最明显的方法是结合结果;

SELECT Depts.Department, 'Poor', COUNT(*)
FROM `Employees`, `Depts`
WHERE Depts.Dept = Employees.Dept AND Employees.Salary <= 100000
GROUP BY Depts.Department

UNION

SELECT Depts.Department, 'Rich', COUNT(*)
FROM `Employees`, `Depts`
WHERE Depts.Dept = Employees.Dept AND Employees.Salary > 100000,
GROUP BY Depts.Department

答案 1 :(得分:0)

包括GROUP BY中的IF逻辑

public partial class Role
{
    public Role()
    {
        Permissions = new HashSet<Permission>();
    }

    [Key]
    public int RoleId { get; set; }

    public string RoleName { get; set; }
    public Virtual ICollection<Permission> Permissions { get; set; } //Notice the virtual?!
}