2016-11-24 42 views
1

我需要獲得updatedtime(最新)desc的前1條記錄訂單。我無法從我的表過濾器頂部1記錄如何使用linq在SQL Server中使用desc獲取每個組訂單的前1條記錄

select watertowerid, DOValue, PHValue, WaterTemperature, CurrentTime 
from ParkingSlots 
group by watertowerid, PHValue, DOValue, WaterTemperature, CurrentTime 

的樣本數據:

PHValue DOValue WaterTemperature watertowerid CurrentTime 
--------------------------------------------------------------------------- 
3.00  4.00  22.00    1   2016-09-29 02:34:00 
6.00  4.00  33.00    2   2016-11-29 02:34:00 
8.22  6.55  28.22    1   2016-06-25 01:25:00 
30.52  5.60  27.00    2   2016-08-29 02:34:00 

所需的輸出:

PHValue DOValue WaterTemperature watertowerid CurrentTime 
--------------------------------------------------------------------------- 
    3.00  4.00   22.00    1   2016-09-29 02:34:00 
    6.00  4.00   33.00    2   2016-11-29 02:34:00 

回答

2

WITH TIES

select TOP(1) with ties * 
from ParkingSlots 
order by row_number() over(partition by watertowerid order by CurrentTime DESC); 
+0

你有什麼想法如何在LINQ中寫這個查詢 – Swapna

+0

Linq沒有直接的模擬。請參閱此主題的選項http://stackoverflow.com/questions/22157211/linq-to-entities-equivalent-of-sql-topn-with-ties – Serg

0

使用Row_number()功能,並找到最新的行基於CURRENTTIME列值。

SELECT [PHValue], [DOValue], [WaterTemperature], [watertowerid], [CurrentTime] 
    FROM (SELECT *, 
        Row_number() 
        OVER(
         partition BY [watertowerid] 
         ORDER BY currenttime DESC) rno 
      FROM ParkingSlots)a 
    WHERE rno = 1 
+0

它的correct.canü幫助我如何寫linq查詢 – Swapna

+0

@Swapna對不起,我不知道linq。 – Buddi

0
CREATE TABLE Table2 
    (PHValue int, DOValue int, WaterTemperature int, watertowerid int, CurrentTime datetime) 
; 

INSERT INTO Table2 

VALUES 
    (3.00, 4.00, 22.00, 1, '2016-09-29 02:34:00'), 
    (6.00, 4.00, 33.00, 2, '2016-11-29 02:34:00'), 
    (8.22, 6.55, 28.22, 1, '2016-06-25 01:25:00'), 
    (30.52, 5.60, 27.00, 2, '2016-08-29 02:34:00') 
; 


;WITH cte AS 
(
    SELECT *, 
     ROW_NUMBER() OVER (PARTITION BY watertowerid ORDER BY CurrentTime DESC) AS rn 
    FROM Table2 
) 
SELECT * 
FROM cte 
WHERE rn = 1 

SELECT * 
FROM Table2 D 
WHERE CurrentTime = (SELECT MAX(CurrentTime) FROM Table2 WHERE watertowerid = D.watertowerid) 
+0

這裏是什麼table2?我只有一個表 – Swapna

+0

表名.. @ swapna – Chanukya

0

在使用LINQ(這是假設實體框架,其他的供應商將是相似的):

var res = from ps in context.ParkingSlots 
      group new { ps.watertowerid, ps.PHValue, ps.DOValue, ps.WaterTemperature, ps.CurrentTime } into groups 
      from grp in groups 
      let top = (from ps in grp 
        orderby ps.updatedtime 
        select ps).FirstOrDefault() 
      where top != null 
      select top; 

應該這樣做。第二個from遍歷允許排序的組,並因此在每個組中都有FirstOrDefault。應該不需要空檢查(需要一個空組),但是對於EF到實體,您不能在內部查詢上使用First

+0

出現錯誤。無效的表達式術語「by」和名稱「g」在當前上下文中不存在 – Swapna

+0

@Swapna錯別字:現在應該被修復(但是這是一個答案草圖,讓您朝着正確的方向而不是經過測試的解決方案)。 – Richard

相關問題