0

我有一张要清理的表,所以我只需要表中的第一个地址ClientId

Addresses有这些列

Pk[Id]
[ClientId]
[AddressLine1]
[AddressLine2]

我使用的查询:

SELECT *
FROM Addresses
ORDER BY ClientId

结果 =

1   1   foo     bar
2   1   foo2    bar2
3   1   foo3    bar3
4   1   foo4    bar4
5   2   foo     bar2
95  2   foo     bar5
97  2   foo     bar6
8   3   foo2    bar7

想要的结果=

1   1   foo     bar   <--is first match for clientid = 1
5   2   foo     bar2  <-- is first match for clientid = 2
8   3   foo2    bar7  <-- is first match for clientid = 3

这需要为 n 个客户端工作

我试过了

SELECT *
FROM Addresses
GROUP BY ClientId

结果错误是(列 'Id' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。)

我在这里想念什么?

4

4 回答 4

2

您得到多行是因为您选择了一个不想作为分组依据的字段。如果您只想要每个 clientID 的第一个条目,则可以使用 ROW_NUMBER 之类的分析函数尝试:

SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY clientid ORDER BY ID) as RowRank
      FROM Addresses)sub
WHERE RowRank = 1
于 2013-06-20T16:13:52.760 回答
2

SQL Server requires that when using a GROUP BY you need to either use an aggregate function on the columns in the select list or add them to the GROUP BY.

Your original query could be changed to use the following:

select a.id, a.clientid, a.address1, a.address2
from addresses a
inner join
(
    select clientid, MIN(id) id
    from addresses
    group by clientid
) d
    on a.clientid = d.clientid
    and a.id = d.id;

As you can see this uses a subquery that returns the min(id) for each clientId, this only groups by the clientid. You then join this to your table to return only those rows with the min id for each client.

于 2013-06-20T16:17:33.540 回答
1

你做了选择 *。选择列表中的每个字段都必须在 GROUP BY 子句中或在聚合函数(MAX、MIN、SUM、AVG 等)中。

这解释了错误。有关解决您的问题的 SQL,请参阅 Goat_CO 答案。

于 2013-06-20T16:15:15.553 回答
0

根据单值规则:选择列表中的所有列必须明确地属于 GROUP BY 条件,或者在聚合函数中,例如 COUNT()、MAX() 等。

于 2013-06-20T16:15:40.563 回答