我有问题要得到我需要的结果:/这些是我的平板电脑。在Postgresql上
table: logins table: users
+------------------------+ +------------------+
| iduser | date | | iduser | name |
|------------------------| |------------------|
| 1 |'2017-06-06'| | 1 | Joe |
|------------------------| |------------------|
| 1 |'2017-06-06'| | 2 | Jane |
|------------------------| |------------------|
| 2 |'2017-06-07'| | 3 | Mary |
|------------------------| +------------------+
| 3 |'2017-06-07'|
|------------------------|
| 3 |'2017-06-07'|
|------------------------|
| 3 |'2017-06-07'|
+------------------------+
我使用此查询:
SELECT name, date, count(*) FROM logins l
LEFT JOIN users u
ON u.iduser= l.iduser
GROUP BY
u.name,l.date
ORDER BY
l.date
这就是我得到的:
+-----------------------------------+
| name | date | count |
|-----------------------------------|
| Joe | '2017-06-06' | 2 |
|-----------------------------------|
| Jane | '2017-06-07' | 1 |
|-----------------------------------|
| Mary | '2017-06-07' | 3 |
+-----------------------------------+
但我真正需要从结果中得到它:
+-----------------------------------+
| name | date | count |
|-----------------------------------|
| Joe | '2017-06-06' | 2 |
|-----------------------------------|
| Jane | '2017-06-06' | 0 |
|-----------------------------------|
| Mary | '2017-06-06' | 0 |
|-----------------------------------|
| Joe | '2017-06-07' | 0 |
|-----------------------------------|
| Jane | '2017-06-07' | 1 |
|-----------------------------------|
| Mary | '2017-06-07' | 3 |
+-----------------------------------+
我该怎么办?请帮忙!!!非常感谢! ^^
答案 0 :(得分:3)
在SQL Server& Postgres的:
获取date
和users
的所有组合,然后left join
到login
的所有组合:
select
d.date
, u.name
, count(l.iduser) as login_count
from (select distinct date from logins) d
cross join users u
left join logins l
on l.iduser=u.iduser
and l.date=d.date
group by d.date, u.name
rextester demo(sql server):http://rextester.com/THJE85313
rextester demo(postgres):http://rextester.com/BNHE97192
返回:
+---------------------+------+-------------+
| date | name | login_count |
+---------------------+------+-------------+
| 2017-06-06 00:00:00 | Jane | 0 |
| 2017-06-07 00:00:00 | Jane | 1 |
| 2017-06-06 00:00:00 | Joe | 2 |
| 2017-06-07 00:00:00 | Joe | 0 |
| 2017-06-06 00:00:00 | Mary | 0 |
| 2017-06-07 00:00:00 | Mary | 3 |
+---------------------+------+-------------+