我有这张表/视图:
Department number_of_customers number_of_employess
dep1 10 15
dep3 20 18
dep1 11 11
dep2 6 8
dep2 20 1
我想按部门分组,然后对每个分组记录进行分组,计算具有特定属性的行 例如number_of_customer> number_of_employees
我当前的查询如下所示:
SELECT dep,count(*) FROM My_table WHERE n_of_cust > n_of_employees GROUP BY dep
但这不是我想要的,因为
例如,dep1没有出现在结果表中
我希望它能在场。
答案 0 :(得分:2)
number_of_customers > number_of_employees
之类的表达式的值为1
(true)或0
(false)。您可以在SUM()
查询中将GROUP BY
应用于此类表达式。
尝试这样的事情:
SELECT dep,
count(*) totalrows,
SUM(n_of_cust > n_of_employees) many_cust_rows,
SUM(n_of_cust = n_of_employees) equal_cust_rows
FROM My_table
GROUP BY dep
答案 1 :(得分:1)
您应该使用同一个表格的JOIN
。类似的东西:
SELECT t1.dep, s1.quantity
FROM My_table AS t1
LEFT JOIN (SELECT dep,count(*)
FROM My_table
WHERE n_of_cust > n_of_employees
GROUP BY dep
) AS s1 ON t1.dep = d1.dep