我有下表和一个SQL查询来确定表中的任何商品的购买价格是否高于卖价。
查询:
SELECT id, name
FROM orders
GROUP BY id, name
HAVING MAX(CASE WHEN buy = 'false' THEN price END) > MIN(CASE WHEN buy = 'true' THEN price END)
问题是这只返回两行:
我正在寻找的结果应该显示购买价格高于所有列的卖价的所有商品。阅读GROUP BY
我发现它只返回不同的值。我是否必须使用连接来实现最终结果?
|id |buy |date |price |name
--------------------------------------------------
3 false 2017-01-04 19:23:12.000 7 bread
3 false 2017-01-04 19:23:12.000 4 bread
2 false 2017-01-04 19:23:12.000 7 grapes
使用此查询的结果是下面的表格,红色突出显示的行不应该在那里。
SELECT *
FROM orders
WHERE id IN (SELECT id
FROM orders
GROUP BY id, name
HAVING MAX(CASE WHEN buy = 'false' THEN price END) > MIN(CASE WHEN buy = 'true' THEN price END))
答案 0 :(得分:1)
将现有查询用作子查询:
SELECT * from orders where id in
(
SELECT id
FROM orders
GROUP BY id, name
HAVING MAX(CASE WHEN buy = 'false' THEN price END) > MIN(CASE WHEN buy = 'true' THEN price END)
)