WITH vTable1 AS (
SELECT PartNumber
FROM Inventory
WHERE Quantity > 1
)
SELECT
[A whole bunch of conditions for tags] +
CASE WHEN vTable1.PartNumber IS NOT NULL THEN 'yes' ELSE 'no' END AS 'TagValue'
FROM Inventory
LEFT JOIN vTable1 ON Inventory.PartNumber = vTable1.PartNumber
所以这是我试图做的一个非常一般的例子,所以请耐心等待。
这个想法在我的CTE中,我有一组条件返回PartNumbers列表。我只想在返回给我的PartNumber超过10个时才添加标记值。否则,请留空。
我设置的当前方式加入vTable1而不考虑行数。
如果CTE超过10行,我将如何仅添加标记值?
由于
答案 0 :(得分:1)
使用if / then logic
If [your condition]
begin
SELECT
[A whole bunch of conditions for tags] +
[ADD TAG]'TagValue'
FROM Inventory
LEFT JOIN vTable1 ON Inventory.PartNumber = vTable1.PartNumber
end
else
begin
SELECT
[A whole bunch of conditions for tags] +
[no tag added]
FROM Inventory
LEFT JOIN vTable1 ON Inventory.PartNumber = vTable1.PartNumber
end
答案 1 :(得分:1)
解决方案是在子查询中使用计数:
WITH vTable1 AS (
SELECT PartNumber
FROM Inventory
WHERE Quantity > 1
)
SELECT
[A whole bunch of conditions for tags] +
CASE WHEN (SELECT COUNT(1) FROM vTable1 AS X) >= 10 THEN 'yes' ELSE 'no' END AS 'TagValue'
FROM Inventory
LEFT JOIN vTable1 ON Inventory.PartNumber = vTable1.PartNumber
另一个是在CTE中使用窗口COUNT()
。
WITH vTable1 AS (
SELECT PartNumber, TotalParts = COUNT(1) OVER()
FROM Inventory
WHERE Quantity > 1
)
SELECT
[A whole bunch of conditions for tags] +
CASE WHEN vTable1.TotalParts >= 10 THEN 'yes' ELSE 'no' END AS 'TagValue'
FROM Inventory
LEFT JOIN vTable1 ON Inventory.PartNumber = vTable1.PartNumber