我有一个名为sites的表,其中有多个同名记录。例如:
Owner Name Owner Address
A XYZ
A ABC
B QWE
B JKL
C ZXC
B BNM
我的sql查询应返回
A1 XYZ
A2 ABC
B1 QWE
B2 JKL
B3 BNM
C ZXC
有人可以给我指点编写这样的查询。我有问题将具有相同所有者名称的记录分组,然后每次为不同的所有者名称应用序列。
答案 0 :(得分:0)
您没有提到您正在使用的数据库系统( SQL =结构化查询语言 - 这是一种查询语言 - 而不是数据库系统......) - 但如果您正在使用SQL Server 2005或更新或任何其他支持CTE(公共表表达式)和ROW_NUMBER
函数的RDBMS,您可以使用:
;WITH data AS
(
SELECT OwnerName, OwnerAddress,
RN = ROW_NUMBER() OVER(PARTITION BY OwnerName ORDER BY OwnerAddress)
FROM dbo.YourTable
)
SELECT
OwnerName + CAST(RN AS CHAR(1)), OwnerAddress
FROM Data
返回输出:
答案 1 :(得分:0)
SELECT OwnerName + Convert(NVARCHAR(10), ROW_NUMBER() OVER (PARTITION BY OwnerName ORDER BY OwnerName)),
OwnerAddress
FROM dbo.OwnerTable
答案 2 :(得分:0)
试试这个:如果您使用的是SQL Server 2005或更高版本
;with cte as (select *,ROW_NUMBER() over(partition by Owner_Name
order by Owner_Address desc) as row_num from sites),
cte1 as(select Owner_Name
from cte
group by Owner_Name
having COUNT(*)>1)
select case when C.Owner_Name in (select Owner_Name from cte1)
then Owner_Name+CAST(row_num as varchar(10))
else Owner_Name end as Owner_Name,Owner_Address
from cte C
order by Owner_Name
结果集