我有一个查询,预期达到以下目的
If((Select count(*) from table1 where product = 'carrot')< 5)
Begin
Select Top (5 - (Select count(*) from table1 where product = 'carrot'))
id, product From table2
WHere id NOT IN
(Select id from table1) AND product = 'carrot'
Order by newid()
END
我想做的是Union或Union都说另一个产品土豆
If((Select count(*) from table1 where product = 'potato')< 5)
Begin
Select Top (5 - (Select count(*) from table1 where product = 'potato'))
id, product From table2
WHere id NOT IN
(Select id from table1) AND product = 'potato'
Order by newid()
END
当我在IF之间或END之后添加UNION时,我一直收到语法错误。这是可能的还是另一种更好的方法。...
我正在做的是尝试选择一个随机的胡萝卜样本,首先我想检查一下表1中是否有5个胡萝卜。如果我不运行示例。 如果我没有5根胡萝卜,请运行采样器并返回5根胡萝卜。然后,我通过ID筛选出它们是否已存在于表1中。然后从新样本中减去总数为5的计数。
效果很好,现在我想运行其他产品,例如生菜,土豆等... 但是我想要一个UNION或UNION All。希望是有道理的。
答案 0 :(得分:1)
我很想知道这种方式是否有效-
Select Top (5 - (Select count(*) from table1 where product = 'carrots')< 5)
id
, product
From table2
WHere id NOT IN (Select id from table2)
AND (Select count(*) from table1 where product = 'carrots')< 5)
UNION ALL
Select Top (5 - (Select count(*) from table1 where product = 'potatoes')< 5)
id
, product
From table2
WHere id NOT IN (Select id from table2)
AND (Select count(*) from table1 where product = 'potatoes')< 5)
您的风格很有趣,感觉是过程性的,而不是基于集合的。
答案 1 :(得分:1)
您可以尝试这种方式
If(((Select count(*) from table1 where product = 'carrot'< 5) and (Select count(*) from table1 where product ='potato' <5))
)
Begin
Select Top (5 - (Select count(*) from table1 where product = 'carrot')) id, product
From table2
WHere id NOT IN (Select id from table1) AND product = 'carrot' Order by newid()
Union all
Select Top (5 - (Select count(*) from table1 where product = 'potato')) id, product From table2
WHere id NOT IN (Select id from table1) AND product = 'potato' Order by newid()
END
答案 2 :(得分:0)
IF
语句在SQL中不充当子查询或行集。它们仅用于分支控制流。
您可以采用以下基于集合的方法:
SELECT ProdSamples.*
FROM
(
SELECT Table2.*, ROW_NUMBER() OVER (PARTITION BY table2.Product ORDER BY NEWID()) RowNum
FROM Table2
LEFT JOIN Table1
ON Table1.id = Table2.id
WHERE Table1.id IS NULL
) ProdSamples
JOIN
(
SELECT Product, COUNT(*) ProdCount
FROM Table1
GROUP BY Product
) ProdCounts
ON ProdSamples.Product = ProdCounts.Product
AND ProdSamples.RowNum <= (5 - ProdCounts.ProdCount)
第一个子查询ProdSamples
返回Table2
中id
中没有Table1
的所有产品。 RowNum
字段按Product
划分的随机顺序对它们进行排名。
第二个子查询ProdCounts
是Table1
中每个产品的记录数。然后它将这些子查询连接在一起,仅返回ProdSamples
处RowNum
小于或等于要返回的样本数的记录。