我正在对SQL表进行查询,该表具有多个列以及多行数据,并且查询根据查询中给出的条件为每个唯一的第一列和第二列返回一行。
例如,我有下表CC
product term bid offer bidcp offercp
AA sep14 20 10 x y
AA Sep14 15 9 p q
BA Sep14 30 15 as ps
XY Sep14 25 15 r t
XY Oct14 30 20 t r
XY Oct14 25 22 p q
当我在上表上运行查询时,它应该返回以下数据
product term bid offer bidcp offercp
AA sep14 20 9 x q(coming from a record which has lowest offer)
BA Sep14 30 15 as ps
XY Sep14 25 15 r t
XY Oct14 30 20 t r
当我执行以下查询时,它甚至通过bidcp和offercp将数据分组到CC
,并返回几乎所有行,因为offercp
和bidcp
在一个或另一个中是唯一的方式,但我只希望bidcp
和offercp
成为bid
和offer
的假设,假设bid
和offer
对都是唯一的对于每个产品和术语
select product,term,max(bid) as bid,min(offer) as offer,bidcp,offercp from canadiancrudes where product like '%/%' group by product,term,bidcp,offercp
但是,当我从groupby子句中删除bidcp和offercp时,它给我一个明显的错误
Column 'CC.BidCP' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
有更好的解决方法吗?
答案 0 :(得分:1)
在这种情况下,您需要2个CTE:
WITH o AS (
SELECT product,term,offer,offercp, ROW_NUMBER() OVER (PARTITION BY product, term ORDER BY offer ASC) AS rn
FROM canadiancrudes where product like '%/%'
)
, b AS (
SELECT product,term,bid,bidcp, ROW_NUMBER() OVER (PARTITION BY product, term ORDER BY bid DESC) AS rn
FROM canadiancrudes where product like '%/%'
)
SELECT o.product,o.term,b.bid,o.offer,b.bidcp,o.offercp
FROM o
INNER JOIN b
ON o.product=b.product
AND o.term=b.term
WHERE o.rn=1
AND b.rn=1
答案 1 :(得分:0)
使用CTE获取最小值,最大值 -
WITH MaxMin_CTE AS (
SELECT product,term,max(bid) as bid,min(offer) AS Offer
FROM CC
GROUP BY product,term)
SELECT * from CC
INNER JOIN MaxMin_CTE ON CC.product = MaxMin_CTE .product
AND CC.bid= MaxMin_CTE.bid AND CC.Offer = MaxMin_CTE.offer
AND CC.Term = MaxMin_CTE.Term
继承人的SQL小提琴 - http://sqlfiddle.com/#!6/a6588/2