根据其他过滤器/条件进行过滤

时间:2019-01-15 00:58:19

标签: sql-server tsql

尝试过滤a,b和c(但仅当> z时才使用c)

在下面进行以下查询。我想选择ItemC记录,但仅当b.Price> 49.99时,同时仍选择所有ItemA和ItemB记录。我该如何修改查询?

SELECT a.ItemType, b.Price
FROM Items a
INNER JOIN Sales b
   ON b.ItemID = a.ItemID
WHERE b.SalesDT >= '1 DEC 18'
AND b.MarketID in (1,3)
AND b.MethodID = 3
AND a.ItemType in ('ItemTypeA','ItemTypeB','ItemTypeC')
GROUP BY a.ItemType
ORDER BY b.Price 
   DESC

因此,如果所有3个ItemType的价格范围都在40.00-54.99之间,我希望提取ItemTypeA和ItemTypeB的所有大小,但仅提取价格> 49.99的ItemTypeC

2 个答案:

答案 0 :(得分:0)

如果我理解正确,我想您只需要添加两个谓词OR:

SELECT a.ItemType, b.Price
FROM Items a
INNER JOIN Sales b
ON b.ItemID = a.ItemID
WHERE b.SalesDT >= '1 DEC 18'
AND b.MarketID in (1,3)
AND b.MethodID = 3
AND (
    a.ItemType in ('ItemTypeA','ItemTypeB')
    OR 
    (a.ItemType ='ItemTypeC' AND b.Price > 49.99) 
) 
GROUP BY a.ItemType
ORDER BY b.Price 
DESC

是您需要的吗?

答案 1 :(得分:0)

尝试一下

SELECT a.ItemType, b.Price
FROM Items a
INNER JOIN Sales b
ON b.ItemID = a.ItemID
WHERE b.SalesDT >= '1 DEC 18'
AND b.MarketID in (1,3)
AND b.MethodID = 3
AND 
(
    a.ItemType in ('ItemTypeA','ItemTypeB'
)


GROUP BY a.ItemType
ORDER BY b.Price 
DESC

union all

SELECT a.ItemType, b.Price
FROM Items a
INNER JOIN Sales b
ON b.ItemID = a.ItemID
WHERE b.SalesDT >= '1 DEC 18'
AND b.MarketID in (1,3)
AND b.MethodID = 3
And
    (a.ItemType ='ItemTypeC' AND b.Price > 49.99) 

GROUP BY a.ItemType
ORDER BY b.Price 
DESC