我无法获得所需的SQL结果

时间:2016-01-13 13:23:34

标签: sql sql-server

我有两张桌子:

所有者

+----+------+------------+
| id | name | birth_year |
+----+------+------------+
|  1 | John |       1970 |
|  2 | Jane |       1980 |
|  3 | Jack |       1990 |
|  4 | Josh |       2000 |
+----+------+------------+

Buylog

+----+----------+------------+
| id | owner_id |    date    |
+----+----------+------------+
|  1 |        1 | 01/01/2016 |
|  2 |        2 | 01/02/2016 |
|  3 |        2 | 01/03/2016 |
|  4 |        1 | 01/04/2016 |
+----+----------+------------+

我需要从Owners表中获取所有信息以及每个所有者的购买次数:

+-----------+-------------+-------------------+--------------+
| owners.id | owners.name | owners.birth_year | buylog.Count |
+-----------+-------------+-------------------+--------------+
|         1 | John        |              1970 |            2 |
|         2 | Jane        |              1980 |            2 |
|         3 | Jack        |              1990 |            0 |
|         4 | Josh        |              2000 |            0 |
+-----------+-------------+-------------------+--------------+

我尝试了以下查询,但返回错误:

Select
  o.id,
  o.name,
  o.birth_year,
  Count(b.id) as Count
From
  owners o
Left Outer Join
  buylog b
On
  b.owner_id = o.id

3 个答案:

答案 0 :(得分:5)

错误消息应该非常清楚,您缺少group by子句:

  Select
  o.id,
  o.name,
  o.birth_year,
  Count(b.id) as Count
From
  owners o
Left Outer Join
  buylog b
On
  b.owner_id = o.id
Group By o.id,
  o.name,
  o.birth_year

答案 1 :(得分:1)

HoneyBadger查询会很好,但可能表现更好:

SELECT o.id
    , o.name
    , o.birth_year
    , COALESCE(b.Count, 0) AS Count
FROM owners o
LEFT JOIN (
    SELECT owner_id, COUNT(*) AS Count
    FROM buylog
    GROUP BY owner_id
    ) AS b
    ON b.owner_id = o.id;

它应该带来完全相同的结果。

答案 2 :(得分:0)

([,.]0?0)?