产品代码在查询中重复

时间:2013-09-10 02:28:58

标签: sql sql-server

我有这张桌子

产品

IDProd ||名称

Time_Price

IDPrice || IDProd ||价格||时间

查询是:

SELECT P.IDProd,P.Name,TP.Price,MAX(TP.Time)

FROM Product P INNER JOIN Time_Price TP ON P.IDProd=TP.IDProd 

GROUP BY P.IDProd,P.Name,TP.Price

我需要产品代码不重复

1 个答案:

答案 0 :(得分:0)

这将为您提供每种产品的最新Price

SELECT  IDProd, Name,
        IDPrice, Price, Time
FROM
    (
        SELECT  a.IDProd, a.Name,
                b.IDPrice, b.Price, b.Time,
                ROW_NUMBER() OVER (PARTITION BY a.IDProd ORDER BY b.Time DESC) rn
        FROM    Product a
                INNER JOIN Time_price b
                    ON a.IDProd = b.IDProd
    ) a
WHERE   a.rn = 1

不使用窗口功能,

SELECT  a.IDProd, a.Name,
        b.IDPrice, b.Price, b.Time
FROM    Product a
        INNER JOIN Time_price b
            ON a.IDProd = b.IDProd
        INNER JOIN
        (
            SELECT  IDProd, MAX(Time) Time
            FROM    Time_price
            GROUP   BY IDProd
        ) c ON b.IDProd = c.IDProd AND
                b.Time = c.Time