根据 SQL 服务器中的 ID 查找数字的平均值

Finding average of numbers against the ID in SQL Server

假设有两个表,CustomerLimit

Customer 有以下列:

CustomerId (PK)
Name

并且 Limit 有这些列:

LimitId (PK)
Limitvalue
CustomerId (FK)

这是我的示例数据:

客户

CustomerId    Name
----------------------
    1         xyz
    2         abc
    3         uio

限制

LimitValue     CustomerId
-------------------------
  35303000         1
         0         1
         3         1
         0         2
 225140000         2
         3         2

现在当我运行这个查询

select a.Limitvalue, b.CustomerId 
from limit a
left join Customer b on a.CustomerId = b.CustomerId

它将return这样的数据:

此处第一列是限制值,第二列是客户 ID。如您所见,一个 customerid 有多个限制值。我想编写一个查询,显示所有限制值与其特定 ID 的平均值。

我尝试添加 avg 函数。这里的 left join 应该可以完成工作,但它不起作用。任何人都可以通过生成一些与此类似的示例数据并编写其查询来帮助我,以便我理解这个概念吗?非常感谢。

group by b.CustomerId

这个,不是吗?

you need to be specific on how the database should work, so you told it to make the average "by grouping on" if you don't the database try to make the AVG on the full table

SQL Fiddle

MS SQL Server 2017 架构设置:

Results:

| CustomerId | Name |
|------------|------|
|          1 |  bob |
|          2 | jean |

Results:

| LimitId | Limitvalue | CustomerId |
|---------|------------|------------|
|       1 |          0 |          1 |
|       2 |         10 |          1 |
|       3 |        100 |          2 |

查询 3:

select 
  avg(a.Limitvalue),
  b.CustomerId 
from limit a
left join Customer b 
  on a.CustomerId= b.CustomerId
group by b.CustomerId

Results:

|     | CustomerId |
|-----|------------|
|   5 |          1 |
| 100 |          2 |