我应该执行什么SQL查询来获得我期望的结果集?

时间:2017-06-12 16:01:34

标签: sql postgresql

我有问题要得到我需要的结果:/这些是我的平板电脑。在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    |
+-----------------------------------+

我该怎么办?请帮忙!!!非常感谢! ^^

1 个答案:

答案 0 :(得分:3)

在SQL Server& Postgres的:

获取dateusers的所有组合,然后left joinlogin的所有组合:

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 |
+---------------------+------+-------------+