比较同一个表中的两行

时间:2016-07-04 10:15:25

标签: sql

我想比较一个表中两行的值,  表格如下 我想找到-F sku大于正常值的记录

SKU         ASIN        Price    
CT0144      B013VNZNYU  20.99
CT0144-F    B013VNZNYU  17.64

2 个答案:

答案 0 :(得分:1)

试试这个,

DECLARE @table TABLE (
    SKU VARCHAR(50)
    ,ASIN VARCHAR(50)
    ,Price FLOAT
    )

INSERT INTO @table
VALUES (
    'CT0144'
    ,'B013VNZNYU'
    ,'20.99'
    )
    ,(
    'CT0144-F'
    ,'B013VNZNYU'
    ,'17.64'
    )
    ,(
    'CT0144'
    ,'B013VNZNU'
    ,'10.99'
    )
    ,(
    'CT0144-F'
    ,'B013VNZNU'
    ,'18.64'
    )

SELECT *
FROM @table

SELECT A.ASIN
    ,A.FPrice
    ,B.Normal
FROM (
    SELECT ASIN
        ,MAX(PRICE) AS FPrice
    FROM @table t1
    WHERE SKU LIKE '%F'
    GROUP BY ASIN
    ) A
INNER JOIN (
    SELECT ASIN
        ,MAX(PRICE) AS Normal
    FROM @table t1
    WHERE SKU NOT LIKE '%F'
    GROUP BY ASIN
    ) B ON A.ASIN = B.ASIN
WHERE A.FPrice > B.Normal

答案 1 :(得分:0)

试试这个

select t1.SKU,t1.ASIN,t1.Price from table as t1 inner join
(
select ASIN, max(price) as price from table group by ASIN
) as t2 
on t1.ASIN=t2.ASIN and t1.price=t2.price 
where t1.SKU like '%-F'