0

我有这张桌子

产品

IDProd || 姓名

时间_价格

ID价格 || 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

我需要产品代码不重复

4

1 回答 1

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
于 2013-09-10T02:32:15.780 回答