2013-08-22 108 views
0

我一直試圖讓下面的SQLNHibernate/LINQ在子查詢中選擇MAX?

SELECT * 
    FROM dbo.VirtualMachines vm 
    WHERE vm.SequenceId IN (
     SELECT MAX(SequenceId) FROM dbo.VirtualMachines GROUP BY RequestId 
    ) 
    AND vm.DeletedBy IS NULL 

...成LINQ查詢與NHibernate的使用。

我已經能夠得到這方面的工作是基於一個corrolated子查詢的變化:

var allvms = from vms in this.currentSession.Query<Entities.VirtualMachine>() 
      where vms.DeletedBy == null 
      where vms.Id == (
       from activeVms in this.currentSession.Query<Entities.VirtualMachine>() 
       where activeVms.RequestId == vms.RequestId 
       orderby activeVms.Id descending 
       select activeVms.Id).First() 
      orderby vms.RequestId 
      select vms; 

......這給了我...

SELECT * 
    FROM dbo.VirtualMachines vm 
    WHERE vm.SequenceId IN (
     SELECT TOP 1 zvm.SequenceId From dbo.VirtualMachines zvm WHERE zvm.RequestId = vm.RequestId ORDER BY zvm.SequenceId DESC 
    ) 
    AND vm.DeletedBy IS NULL 

。 ..但是,我寧願使用MAX()版本(具有配置文件的SQL Server),這是對我正在使用的數據集的更高效的查詢。不幸的是,我無法弄清楚如何爲LINQ提供查詢。

我知道我可以做:

from vms in this.currentSession.Query<Entities.VirtualMachine>() 
    group vms by vms.RequestId into vmReqs 
    select new { 
     LatestSeqId = vmReqs.Max(vms => vms.SequenceId) 
    } 

這使我的子選擇(SELECT MAX(SequenceId) [...]),但我看不出這與查詢相結合我已經有了做一個IN 。我可能會用SQL來處理這個問題,我試圖按照SQL中的方式來處理查詢,還有一些我錯過的其他技術。

回答

1

事情是這樣的:

var subQuer = from vms in this.currentSession.Query<Entities.VirtualMachine>() 
       group vms by vms.RequestId into vmReqs 
       select vmReqs.Max(vms => vms.SequenceId); 

var outerQuery = from vm in this.currentSession.Query<Entities.VirtualMachine>() 
       where subQuery.Contains(vm.SequenceId) && vm.DeletedBy == null; 
+0

這似乎已經完成了任務,雖然SQL是一個有點笨拙(它包裹子選擇在'EXISTS(SELECT NULL FROM(...)AS t2 WHERE t2.value = t0.SequenceID')它只產生與子查詢相同的執行計劃,這對我來說已經足夠了,我還注意到(通過實驗)我可以將它們合併到單個查詢中 –

+0

@ChrisJ對EXISTS有點驚訝...這是什麼SQL語言? –

+0

差不多相同的查詢不適用於我。'System.Int32'不能用作具有ItemExpression的序列的數據類型鍵入'System.Int32'。 –