如果不是所有行都存在,则来自不同表的sql server计数
我试图从两个表中得到结果。第一个表是带有信息的id,从第二个表中,我想根据某些条件计算第一个表中每个id的现有数量。这是我的密码:如果不是所有行都存在,则来自不同表的sql server计数,sql,sql-server,count,multi-table,Sql,Sql Server,Count,Multi Table,我试图从两个表中得到结果。第一个表是带有信息的id,从第二个表中,我想根据某些条件计算第一个表中每个id的现有数量。这是我的密码: SELECT p.stId, count(att.adate) FROM payments p LEFT JOIN Attendence att ON att.stId = p.stId where p.cyear = 2018 and p.cmonth = 3 and p.cId = 10 and att.adate between '2018/03/01' an
SELECT p.stId, count(att.adate)
FROM payments p
LEFT JOIN Attendence att ON att.stId = p.stId
where p.cyear = 2018 and p.cmonth = 3 and p.cId = 10
and att.adate between '2018/03/01' and '2018/03/30 23:59:59.999' and att.cid
= 10
GROUP BY p.stId
从第一个表(p)中,我有3个ID。但是当我运行它时,它只返回1个id。第二个表(t)中不存在的id不会给出任何结果。我想做的是,如果第二个表中没有id,我想为计数返回一个0(count(att.adate))
谢谢。将右侧表条件从
的WHERE
移动到ON
以获得真正的左连接
结果:
SELECT p.stId, count(att.adate)
FROM payments p
LEFT JOIN Attendence att ON att.stId = p.stId
and att.adate between '2018/03/01' and '2018/03/30 23:59:59.999' and att.cid
= 10
where p.cyear = 2018 and p.cmonth = 3 and p.cId = 10
GROUP BY p.stId
(在
WHERE
中时,您将获得常规的内部联接
结果。)您可能缺少结果,因为在WHERE子句中,您对考勤表中的列设置了条件。对于与付款表不匹配的情况,这些值将为空。所以我会让你这样问:
SELECT p.stId, count(att.adate)
FROM payments p
LEFT JOIN Attendence att ON att.stId = p.stId
where p.cyear = 2018 and p.cmonth = 3 and p.cId = 10
and (att.adate between '2018/03/01' and '2018/03/30 23:59:59.999' OR att.adate IS NULL) and (att.cid
= 10 or att.cid IS NULL)
GROUP BY p.stId
您的问题是,
where
将左连接
转换为内部连接
。我还想简化日期算法:
SELECT p.stId, count(a.adate)
FROM payments p LEFT JOIN
Attendence a
ON a.stId = p.stId AND a.cid = p.cid AND
a.adate >= '2018-03-01' AND
a.adate < '2018-04-01
WHERE p.cyear = 2018 and p.cmonth = 3 and p.cId = 10
GROUP BY p.stId;
选择p.stId,count(a.adate)
从p左连接
出席
关于a.stId=p.stId和a.cid=p.cid和
a、 日期>='2018-03-01'和
a、 adate<'2018-04-01
其中p.cyear=2018,p.cmonth=3,p.cId=10
p.stId分组;
我所做的更改是什么:
- 将第二个表上的筛选条件移动到
子句。这就是左连接的工作方式on
- 我在
上添加了一个cid
条件,因此与JOIN
的比较只发生一次(在10
子句中)WHERE
- 将日期格式更改为YYYY-MM-DD。这与ISO 8601标准日期格式一致
- 将
之间的
更改为
和=
谢谢!!做那件事!!