2013-11-25 41 views
2

在我的表,我有以下值:在SQL Server中,如何選擇共享列值的行?

ProductId Type  Value  Group 
200  Model  Chevy  Chevy 
200  Year  1985  Chevy 
200  Year  1986  Chevy 
200  Model  Ford  Ford 
200  Year  1986  Ford 
200  Year  1987  Ford 
200  Year  1988  Ford 

在我的詢問,我想知道我的產品是在某一年某一型號兼容。我試圖構建一個返回true或false的函數,具體取決於ProductId,Model和Value傳遞給它的參數。爲真,函數必須與表中的ProductId一起匹配兩個參數(Model和Year),但它們必須屬於同一組。

例如,如果我將值200,Chevy,1988傳遞給函數,它必須返回False。請注意,表中可以找到3個值,但它們屬於不同的組。另一方面,如果我傳遞給函數值200,福特,1986,它必須返回真,因爲所有3個值匹配並屬於同一組。

我想這樣做的一種方式是在多個步驟,如:

  1. 選擇模型匹配,則所有匹配的一年,並把它們插入到一個臨時表中的所有記錄;
  2. 選擇不同的組到另一個臨時表;
  3. 循環遍歷每個組,檢查是否找到該組中的所有匹配項,在函數結束時返回true或返回true。

我不知道是否有一個更好的方法,只用一個SELECT命令就可以在1個步驟中執行此操作。

回答

0

要獲得一個查詢都ModelValue,你可以加入本身的表:
(我假設的表被稱爲products

select * 
from products as models 
inner join products as years 
    on models.productid = years.productid 
    and models.group = years.group 
where models.type = 'Model' and years.type = 'Year' 

這會給你排Chevy, 1985,Chevy, 1986,Ford, 1986等等。

然後,您只需將您的值(例如200, Ford, 1986)放入WHERE條款。
所以對於200, Ford, 1986最終的查詢會是這樣的:

select * 
from products as models 
inner join products as years 
    on models.productid = years.productid 
    and models.group = years.group 
where models.type = 'Model' and years.type = 'Year' 
and models.productid = 200 
and models.value = 'ford' 
and years.value = '1986' 
+0

是的,非常聰明的解決方案。那會做。感謝Christian。 –

0

您可能會過度複雜。這應該是足夠了:

select exists(select * from Products where ProductId = 200 and Type = 'Year' and Value = 1986 and Group = 'Ford') 
+0

該組與參數無關。重要的是結果應該屬於同一組。在上面的例子中,我想知道這個特定的產品是否適合(Model = Chevy AND Year = 1988),而不管哪個組模型和年份屬於哪個組,只要它是相同的組。 –

0

如何只計數?

select 
    count(*) 
from 
    products 
where 
    ProductId = @ProductId and 
    (
     (Type = 'Model' and Value = @Model) or 
     (Type = 'Year' and Value = @Year) or 
    ) 

如果計數是2,那麼你已經擊中了。

相關問題