sql statement..how合并这段代码?

时间:2018-01-06 07:14:40

标签: sql visual-studio

dgvall("SELECT department FROM tblvoter GROUP BY department", dgvdepartment)
dgvall("SELECT COUNT(tblvoter.department) AS 'votes', department FROM tblvoter WHERE voterstatus = '1'", dgv123)

如何将其合并为一个SQL语句或合并它?

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

SELECT
    department,
    COUNT(CASE WHEN voterstatus = '1' THEN 1 END) AS voted,
    COUNT(CASE WHEN voterstatus = '0' THEN 1 END) AS no_vote
FROM tblvoter
GROUP BY department;

这将确保每个部门都出现在您的结果集中,即使该部门没有选民也是如此。你当前的潜在问题是,如果一个部门没有选民,那么它将完全从结果集中过滤掉。