0

我有两张桌子:

1. Products with the following columns:
* ID
* SerialNumber
* Name
2. ProductsData
* ID
* ProductID
* DateOfData
* DataValue

我想了解以下内容:

* Product name.
* product serial number
* the last date of data for this product.
* the data value in this datetime

如何通过 SQL 查询来创建视图?

谢谢

4

2 回答 2

1
CREATE VIEW vw_SomeName
AS
SELECT P.Name, P.SerialNumber, PD.DataValue, MAX(PD.DateOfData)
FROM Products P INNER JOIN ProductsData PD
ON P.ID = PD.ProductID
GROUP BY P.Name, P.SerialNumber, PD.DataValue

或者你也可以试试这个

    CREATE VIEW vw_SomeName
    AS
    SELECT P.Name, P.SerialNumber, PD.DataValue, LastDate
    FROM Products P 
                    CROSS APPLY (
                                SELECT TOP 1  PD.DataValue, MAX(PD.DateOfData) AS LastDate
                                FROM ProductsData PD
                                WHERE P.ID = PD.ProductID
                                GROUP BY PD.DataValue
                                ORDER BY LastDate DESC
                                ) PD
于 2013-10-06T11:07:23.793 回答
0

尝试这个

SELECT Name, SerialNumber, ABB3.last_date, ABB3.DataValue 
FROM Products AS ABB4
    LEFT JOIN
        (SELECT ABB2.ProductID, last_date, DataValue
        FROM ProductsData AS ABB2
            LEFT JOIN 
            (SELECT ProductID, MAX(DateOfData) AS last_date
            FROM ProductsData
            GROUP BY ProductID) AS ABB1 ON ABB1.ProductID = ABB2.ProductID 
            AND ABB1.last_date = ABB2.DateOfData)
        AS ABB3 ON ABB3.ProductId = ABB4.ID
于 2013-10-06T12:34:42.863 回答