2015-08-21 42 views
4

我的表SELECT和用於具有2列

ID Name Addr tDate 
------------------------------- 
| 1 | Aa | street | 20151231 
| 2 | Aa | street | 20130202 
| 2 | Aa | street | 20120101 
| 3 | Aa | way | 20150821 
| 4 | Bb | street | 20150821 
| 7 | Xb | street | 20150821 
| 5 | Cc | way | 20150821 
| 5 | Cc | way | 20150821 
| 6 | Cc | no way | 20150821 

結果相同的值的唯一ID創建新的ID 01

ID Name Addr | tDate 
------------------------------- 
| 1 | Aa | street | 20151231 
| 2 | Aa | street | 20130202 
| 2 | Aa | street | 20120101 

將創建一個新的nID 應當原樣複製或合併如果名稱和地址相同並且選擇了ID和最新的tDate

結果02

ID Name Addr  tDate  nID 
------------------------------------ 
| 1 | Aa | street | 20151231 | 1 
| 2 | Aa | street | 20120101 | 1 <-- nID != ID 
| 2 | Aa | street | 20130202 | 1 <-- nID != ID 
| 3 | Aa | way | 20150821 | 3 
| 4 | Bb | street | 20150821 | 4 
| 7 | Xb | street | 20150821 | 7 
| 5 | Cc | way | 20150821 | 5 
| 5 | Cc | way | 20150821 | 5 
| 6 | Cc | no way | 20150821 | 6 

我試過這個。不知道它是否正確。

SELECT DISTINCT dr.* 
       FROM MyTable dr 
       inner join(
        SELECT ID, Name, Addr 
        FROM MyTable 
        GROUP BY ID, Name, Addr 
       ) ss on dr.Name = ss.Name and 
         dr.Addr = ss.Addr and 
         dr.ID <> ss.ID 
       order by Name 
+0

該死的抱歉.. BB和XB有不同的ID - 編輯 – Kaptah

回答

5

編輯:你除了tDate後徹底的改變,以及需要兩個結果集

結果集1:

SELECT 
    id, Name, Addr, tDate 
FROM 
(
    SELECT 
     *, 
     COUNT(*) OVER (PARTITION BY Name, Addr) AS occurrences 
    FROM 
     MyTable 
) 
    AS parsed 
WHERE 
    occurrences > 1 

結果集2:

SELECT 
    *, 
    FIRST_VALUE(ID) OVER (PARTITION BY Name, Addr 
           ORDER BY tDate DESC 
           ROWS UNBOUNDED PRECEDING) AS nID 
FROM 
    MyTable 
ORDER BY 
    ID 

例子:http://sqlfiddle.com/#!6/9285ae/9

+1

'select *'後錯過了逗號' – Wanderer

+0

對於id 4和7,nID不是OP所要求的 – Madhivanan

+0

@Madhivanan - 在最初的問題上,在第一次編輯你是對的,但通過第二次編輯這個答案是正確的。 – MatBailie

1

dense_rank窗函數應該做的伎倆:

SELECT ID, Name, Addr 
     DENSE_RANK() OVER (PARTITION BY Name, Addr ORDER BY ID) AS nID 
FROM  mytable 
ORDER BY 1, 4 
+0

看起來和OP的編輯之後,但仍然在這裏失敗:'要創建一個新的nID它應該複製原樣或合併,如果名稱和地址相同' – MatBailie

-1

您應該使用RANK不分區

SELECT ID, Name, Addr, 
     RANK() OVER (ORDER BY Id,name,addr) AS nID 
FROM  table 
+0

看在OP的編輯後,但仍然失敗:'要創建一個新的nID它應該被複制如果名稱和地址相同,則爲OR,否則合併' – MatBailie

相關問題