2014-02-19 45 views
0

我試圖在不包含與另一產品具有相同折扣百分比的產品的情況下進行查詢。我也想使用子查詢。這就是我想到的,但是我收到一個錯誤消息,說:「子查詢返回的值不止一個,當子查詢跟隨=,!=,<,< =,>>,> =或當子查詢用作表達式。「SQL Server爲每個產品獲取唯一值

SELECT ProductName, 
(SELECT DiscountPercent 
FROM Products 
GROUP BY DiscountPercent 
HAVING COUNT(DiscountPercent) = 1 
) 
FROM Products 

Fender Stratocaster 30.00 
Gibson Les Paul 30.00 
Gibson SG 52.00 
Yamaha FG700S 38.00 
Washburn D10S 0.00 
Rodriguez Caballero 11 39.00 
Fender Precision 30.00 
Hofner Icon 25.00 
Ludwig 5-piece Drum Set with Cymbals 30.00 
Tama 5-Piece Drum Set with Cymbals 15.00 
+0

SELECT產品名稱, (SELECT DiscountPercent FROM產品P1其中p1.ProductName = p.ProductName GROUP BY DiscountPercent HAVING COUNT(DiscountPercent)= 1 ) FROM Products P – KumarHarsh

+0

這是不正確的。我仍然得到3個相同的值3個產品 – jaramore

+0

提供樣本數據,以獲得準確的結果。 select * from (select *,row_number()over(產品名稱,DiscountPercent order by ProductName)rn from Products)t4 其中rn = 1 – KumarHarsh

回答

0

嘗試此,

select * from (
select *,row_number()over (partition by Discount order by ProductName)rn from @t 
)t4 where rn=1 
0
SELECT 
[ProductName], 
[DiscountPercent] 
FROM 
(
SELECT ROW_NUMBER() OVER (PARTITION BY DiscountPercent ORDER BY ProductName) AS [ProductRank], 
[ProductName], 
[DiscountPercent] 
FROM 
[Products] 
) AS Data 
WHERE [ProductRank] = 1