从sql数据库创建一个视图

时间:2013-10-06 10:58:43

标签: sql sql-server database view

我有两张桌子:

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查询来创建视图?

由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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