如何在 SQL 中不包含重复行?
how to NOT have repeating rows in SQL?
我的 schemea 是一个客户 table,他使用地址加入 table。有些地址有两个:账单和送货。
如何通过开票或送货让每条线有一个客户。
我觉得应该使用 DISTINCT,但如果我这样做,它会删除附有账单和送货地址的我的客户。
enter image description here
enter image description here
SELECT
Firstname,
LastName,
Line1,
City,
State,
ZipCode,
FROM
Customers as c
INNER JOIN Addresses as a ON c.CustomerID = a.CustomerID
ORDER BY
c.CustomerID
使用 row_number()over()
和常见的 table 表达式,您可以为每个客户 select table Addresses
的第一行。然后将 table 与客户 table 连接起来,每个客户只有一行。
with addess as
(
select *,row_number()over(partition by customerid order by addressid)rn from Addresses
)
SELECT
Firstname,
LastName,
Line1,
City,
State,
ZipCode,
FROM
Customers as c
INNER JOIN Address as a ON c.CustomerID = a.CustomerID and rn=1
ORDER BY
c.CustomerID
一个较慢的子查询解决方案:
SELECT
Firstname,
LastName,
Line1,
City,
State,
ZipCode,
FROM
Customers as c
INNER JOIN Address as a ON c.CustomerID = a.CustomerID and
a.AddressID=(select min(addressid) from Addresses where CustomerID=c.CustomerID)
ORDER BY
c.CustomerID
我的 schemea 是一个客户 table,他使用地址加入 table。有些地址有两个:账单和送货。
如何通过开票或送货让每条线有一个客户。
我觉得应该使用 DISTINCT,但如果我这样做,它会删除附有账单和送货地址的我的客户。
enter image description here
enter image description here
SELECT
Firstname,
LastName,
Line1,
City,
State,
ZipCode,
FROM
Customers as c
INNER JOIN Addresses as a ON c.CustomerID = a.CustomerID
ORDER BY
c.CustomerID
使用 row_number()over()
和常见的 table 表达式,您可以为每个客户 select table Addresses
的第一行。然后将 table 与客户 table 连接起来,每个客户只有一行。
with addess as
(
select *,row_number()over(partition by customerid order by addressid)rn from Addresses
)
SELECT
Firstname,
LastName,
Line1,
City,
State,
ZipCode,
FROM
Customers as c
INNER JOIN Address as a ON c.CustomerID = a.CustomerID and rn=1
ORDER BY
c.CustomerID
一个较慢的子查询解决方案:
SELECT
Firstname,
LastName,
Line1,
City,
State,
ZipCode,
FROM
Customers as c
INNER JOIN Address as a ON c.CustomerID = a.CustomerID and
a.AddressID=(select min(addressid) from Addresses where CustomerID=c.CustomerID)
ORDER BY
c.CustomerID