2011-03-24 48 views
1

假設在數據庫中的記錄如下:如何使用相同的價值觀得到記錄,除了主鍵

Id   FirstName  LastName  OrderPrice 
1   Tom    Hanks   123 
2   Tom    Hanks   173 
3   Tom    Hanks   123 
4   Tom    Bob    123 
5   Robert   Hanks   123 

Given Input : Id = 1 
Expected OUtput : Id = 3 

我知道我可以寫象下面

Declare @Id as INT = 1 
Declare @FirstName as varchar(100) 
Declare @LastName as varchar(100) 
Declare @OrderPrice as INT 

Select @FirstName = FirstName, @LastName = LastName , @OrderPrice = OrderPrice From Customers Where Id= @ID 

Select ID From Customers Where FirstName = @FirstName and LastName = @LastName and OrderPrice = @OrderPrice 

但有些事情,我不想寫一些東西,比如我應該在哪裏提及所有列名在哪裏。因爲實際上我正在處理的記錄包含了近100列。所以,我被要求不要使用這樣的查詢。

任何人都可以幫助我如何做到這一點?

+1

我認爲你的數據庫設置錯了。你應該有一個鏈接表與名稱,而不是重複它們。然後從該表開始,找到客戶的訂單。如果你在數據庫結構中沒有發言權,它已經設置好了,這個建議沒有多大幫助。 – thursdaysgeek 2011-03-24 19:56:50

+0

這是一個自然按鍵的優良參數:) – Ichorus 2011-03-24 19:58:15

+0

無論如何,如果有多個重複項應該返回什麼?除了您用作查詢輸入的記錄以外的所有記錄?只有第一個重複記錄? – Ichorus 2011-03-24 19:59:17

回答

3

您可以使用動態SQL創建查詢以搜索重複記錄。基本上,這個查詢構建一個字符串像a.col1 = b.col1 and a.col2 = b.col2 and ...並使用它作爲一個在on條款自聯接:

declare @columns varchar(max) 

select @columns = 
      case when @columns is null then 'a.' else @columns + ' and a.' end + 
      quotename(name) + ' = b.' + quotename(name) 
from sys.columns 
where object_id = object_id('YourTable') 
     and name <> 'ID' 

declare @query varchar(max) 
set @query = 'select b.ID from YourTable a ' + 
    'join YourTable b on a.ID <> b.ID and ' + @columns + ' where a.ID = 1' 
exec (@query) 

這種搜索與複製ID = 1,除了ID行。

+0

我認爲,在'和a.'之前缺少空格(在CASE表達式中)。 – 2011-03-24 20:31:30

+1

@Andriy M:編輯!但它仍然工作,因爲'quotename'返回像'a。[col1] = b。[col1]和a。[col2] ...'這似乎是有效的字符串t-sql – Andomar 2011-03-24 20:37:11

+0

確實!我沒有想到這一點。當然,右括號在這裏用作單詞分隔符。 – 2011-03-24 20:45:46

0
Declare @Id as INT = 1 

WITH 
    dupes AS 
    (
     SELECT 
C1.Id, 
      C1.FirstName, 
      C1.LastName, 
      C1.OrderPrice 
     FROM 
      Customers C1 
     LEFT OUTER JOIN Customers C2 
     ON 
      C1.FirstName = C2.FirstName 
     AND C1.LastName = C2.LastName 
     AND C1.OrderPrice = C2.OrderPrice 
     WHERE 
      C1.Id <> C2.Id 
    ) 
SELECT 
    dupes.Id 
FROM 
    Customer 
INNER JOIN dupes 
ON 
    Customer.FirstName = dupes.FirstName 
AND Customer.LastName = dupes.LastName 
AND Customer.OrderPrice = dupes.OrderPrice 
WHERE 
    Customer.Id = @Id 
AND dupes.Id <> @Id 
相關問題