2013-10-06 51 views
0

一個觀點我有兩個表:使得從SQL數據庫

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查詢來進行查看?

感謝

+0

我試着用innerjoin的東西,但它在第二個表中返回所有行。我只想要最後一個數據 – user1902346

+0

@ user1902346下一次,將您的問題與您的問題一起發佈,這樣人們就會知道您在詢問之前需要付出一些努力。這通常會帶來更多的答案和更少的問題。 –

回答

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 
+0

謝謝。我該如何獲得該日期的DataValue? – user1902346

+0

我編輯了代碼看看請:) –

+1

謝謝,但第二個是語法錯誤,第一次返回mee所有行中的產品數據中的日期 – user1902346

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