2012-08-04 50 views
0

我有一個名爲site的表,其中有多個相同名稱的記錄。對於例如:在Oracle 10g的Sql查詢中需要說明

 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 

可能有人給我指點寫這樣的query.I時遇到問題分組記錄有相同的所有者名稱,然後每次申請序列爲不同的所有者名稱。

+1

您正在使用SQL Server或MySQL的數據庫引擎? – 2012-08-04 10:16:22

+0

@JoeGJoseph,還有其他幾個選項: - )./ – Ben 2012-08-04 10:27:42

+0

爲什麼'C'沒有得到一個數字呢? – 2012-08-04 11:30:00

回答

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 

返回的輸出:

enter image description here

0
SELECT OwnerName + Convert(NVARCHAR(10), ROW_NUMBER() OVER (PARTITION BY OwnerName ORDER BY OwnerName)), 
     OwnerAddress 
FROM dbo.OwnerTable 
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 

結果集

enter image description here