在 SQL 中连接两个表时使用 "GROUP BY"
Using "GROUP BY" while joining two tables in SQL
我 运行 遇到了一个我似乎无法弄清楚的问题,也没有在网上找到任何解决方案。
我有两个table;一个有作者,一个有书。我需要总结信息,但我无法使 group by
条件起作用或 count
就此而言,但我认为这是由我的 group by
.[=22= 问题引起的]
我的代码是:
SELECT
a.ID,
a.FirstName + ' ' + a.LastName AS [Name],
CASE WHEN a.DeathDate IS NULL
THEN DATEDIFF(YEAR,a.BirthDate,SYSUTCDATETIME())
ELSE DATEDIFF(YEAR,a.BirthDate,a.DeathDate)
END AS [Age]
,COUNT(a.ID) AS [Books]
FROM Author a LEFT JOIN Books b ON a.ID = b.AuthorID
group by a.ID
如果我删除 count
和 group by
,我会得到一个 table,其中重复了作者的名字,因为有些人已经写了几本书,这是可以预料的。我想做的是计算他们写的书的数量,将其添加为一列并删除名称重复。
Table 没有 group by
& count
:
| ROW | ID | Name | Age |
|-------------|------------|------------|------------|
| 1 | 1 | Adam | 50 |
| 2 | 1 | Adam | 50 |
| 3 | 2 | Sven | 36 |
| 4 | 2 | Sven | 36 |
| 5 | 3 | Eric | 82 |
| 6 | 4 | Rick | 75 |
Table我希望我有:
| ROW | ID | Name | Age | Books |
|-------------|------------|------------|------------|------------|
| 1 | 1 | Adam | 50 | 2 |
| 2 | 2 | Sven | 36 | 2 |
| 3 | 3 | Eric | 82 | 1 |
| 4 | 4 | Rick | 75 | 1 |
有人能帮忙吗?
相关子查询听起来不错:
SELECT
a.ID,
a.FirstName + ' ' + a.LastName AS [Name],
CASE WHEN a.DeathDate IS NULL
THEN DATEDIFF(YEAR,a.BirthDate,SYSUTCDATETIME())
ELSE DATEDIFF(YEAR,a.BirthDate,a.DeathDate)
END AS [Age]
,q1.books_count AS [Books]
FROM
Author a
outer apply(
select count(*) as books_count
from Books b
where a.ID = b.AuthorID
) as q1
我 运行 遇到了一个我似乎无法弄清楚的问题,也没有在网上找到任何解决方案。
我有两个table;一个有作者,一个有书。我需要总结信息,但我无法使 group by
条件起作用或 count
就此而言,但我认为这是由我的 group by
.[=22= 问题引起的]
我的代码是:
SELECT
a.ID,
a.FirstName + ' ' + a.LastName AS [Name],
CASE WHEN a.DeathDate IS NULL
THEN DATEDIFF(YEAR,a.BirthDate,SYSUTCDATETIME())
ELSE DATEDIFF(YEAR,a.BirthDate,a.DeathDate)
END AS [Age]
,COUNT(a.ID) AS [Books]
FROM Author a LEFT JOIN Books b ON a.ID = b.AuthorID
group by a.ID
如果我删除 count
和 group by
,我会得到一个 table,其中重复了作者的名字,因为有些人已经写了几本书,这是可以预料的。我想做的是计算他们写的书的数量,将其添加为一列并删除名称重复。
Table 没有 group by
& count
:
| ROW | ID | Name | Age |
|-------------|------------|------------|------------|
| 1 | 1 | Adam | 50 |
| 2 | 1 | Adam | 50 |
| 3 | 2 | Sven | 36 |
| 4 | 2 | Sven | 36 |
| 5 | 3 | Eric | 82 |
| 6 | 4 | Rick | 75 |
Table我希望我有:
| ROW | ID | Name | Age | Books |
|-------------|------------|------------|------------|------------|
| 1 | 1 | Adam | 50 | 2 |
| 2 | 2 | Sven | 36 | 2 |
| 3 | 3 | Eric | 82 | 1 |
| 4 | 4 | Rick | 75 | 1 |
有人能帮忙吗?
相关子查询听起来不错:
SELECT
a.ID,
a.FirstName + ' ' + a.LastName AS [Name],
CASE WHEN a.DeathDate IS NULL
THEN DATEDIFF(YEAR,a.BirthDate,SYSUTCDATETIME())
ELSE DATEDIFF(YEAR,a.BirthDate,a.DeathDate)
END AS [Age]
,q1.books_count AS [Books]
FROM
Author a
outer apply(
select count(*) as books_count
from Books b
where a.ID = b.AuthorID
) as q1