2009-08-22 10 views
0

Ich habe eine Eltern-Tabelle 'ProductCategory' und eine Kind-Tabelle 'Produkt'. Ich habe diese Abfrage, die 3 zufällige Produkte zurückgibt:sql Server 2005 Abfrage - zufällige Kind Zeilen von UNIQUE zufällige Eltern Zeilen

SELECT TOP (3) ProductId 
FROM  Product 
ORDER BY NEWID(); 

Ich möchte diese Abfrage zu verbessern, um zu erreichen, dass alle Produkte aus verschiedenen Produktkategorien. So ist die Abfrage eindeutige Kategorien würden zu bekommen:

SELECT TOP (3) ProductCategoryId 
FROM  ProductCategory 
ORDER BY NEWID(); 

Ich bin, um herauszufinden, nicht in der Lage, wie diese zwei Abfragen zu kombinieren, um mein Ziel zu erreichen. Die offensichtliche Abfrage

SELECT TOP (3) p.ProductId 
FROM  Product p 
where p.productcategory_ProductCategoryId in 
    (
    SELECT TOP (3) ProductCategoryId pc 
    FROM  ProductCategory pc 
    ORDER BY NEWID() 
    ) 
ORDER BY NEWID(); 

funktioniert nicht. Es scheint, dass die innere select-Anweisung ignoriert wird. Ich habe es auch mit der EXISTS-Anweisung versucht oder bin den Tabellen beigetreten. Alle mit dem gleichen Ergebnis.

Hat jemand eine Idee? Vielen Dank im Voraus!

Antwort

0

Wie wäre es mit so etwas? Ich konnte diese Aufgabe mithilfe einer temporären Tabelle und eines Cursors ausführen. Länger von einem Schritt, aber es funktioniert.

create table #temp(
productID int 
,CategoryID int 
) 
declare @CategoryID int 
declare ID_Cursor cursor 
for select ProductCategoryID from ProductCategory order by NEWID() 
open ID_Cursor 
FETCH NEXT FROM ID_Cursor INTO @CategoryID 

WHILE @@FETCH_STATUS = 0 and (select COUNT(*) from #temp)<3 
BEGIN 

if (@CategoryID not in (select CategoryID from #temp)) 
Begin 
insert into #temp 
SELECT top(1) ProductID, @CategoryID 
    FROM [Product] 
    order by NEWID() 
END 

FETCH NEXT FROM ID_Cursor INTO @CategoryID 
END 
CLOSE ID_Cursor 
DEALLOCATE ID_Cursor 

select * from #temp 
drop table #temp 
1

Sie haben 2-Abfragen zu entkoppeln und dies ist eine Lösung

Per ProductCategoryID korrelierte Unterabfrage ein zufälliges Produkt zu erhalten. Die Eindeutigkeit von ProductCategoryId wird von der äußeren Abfrage verarbeitet.

SELECT TOP 3 
    (SELECT TOP 1 
     ProductId 
    FROM 
     Product P 
    WHERE 
     P.ProductCategoryId = PC.ProductCategoryId 
    ORDER BY 
     NEWID() 
    ) AS ProductId 
FROM 
    ProductCategory PC 
WHERE 
    EXISTS (SELECT * 
     FROM 
      Product Pex 
     WHERE 
      Pex.ProductCategoryId = PC.ProductCategoryId) 
ORDER BY 
    NEWID(); 
1

Ich habe es jetzt!

In Burbidge87 die habe ich eine, wo Bedingung:

FROM Product p 
where @CategoryID = p.ProductCategory_ProductCategoryId 

, die es tut. Danke noch einmal!

JJ

Verwandte Themen