2013-04-24 35 views
1

具有以下表結構粗糙的Linq查詢

table structure

我需要改編的由狀態,其中記錄沒有一個工作流文件夾中的計數。這確實的伎倆:

from p in Transcriptions 
where p.WorkflowfolderID == null 
group p by p.TranscriptionStatus.Description into grouped 
select new 
{ 
    xp=grouped.Key, 
    xp1= grouped.Count(), 
} 

現在我需要通過date.Something像

EntityFunctions.DiffHours(p.DueOn,DateTime.Today)>0 

如何做補充的記錄數,其中Dueon日期是過去在它是過去由於我將它包含在結果集中而不觸發2個SQL查詢?我很高興把它作爲第三列,每行都有相同的值。無論如何,有百分比混合如下:

狀態| Count | %|
------------------------------
Status1 | 20 | 20%
狀態2 | 30 | 30%
狀態3 | 30 | 30%
逾期| 20 | 20%

我已經添加了Overdue作爲一行,但非常樂意將它作爲具有相同值的列。

編輯的內容

嗯,這是我能拿出最好的。它不是一個單一的查詢,但只有一個SQL旅程。其結果是:

狀態1計數
----------------
狀態1 | 20
狀態2 | 30
狀態3 | 30
逾期| 20

var q1= from p in Transcriptions 
    where p.WorkflowfolderID == null 
    group p by p.TranscriptionStatus.Description into grouped 
    select new 
    { 
     status= (string)grouped.Key, 
     count= grouped.Count() 
    }; 

    var q2 =(
     from p in Transcriptions select new {status = "Overdue", 
     count = (from x in Transcriptions 
     where x.DueOn.Value < DateTime.Now.AddHours(-24) 
     group x by x.TranscriptionID into 
     grouped select 1).Count() }).Distinct(); 
    q1.Union(q2) 

它一旦結果返回給做與計算%一個聯盟條款。奇怪的是,我無法找出任何干淨的方式來表示LINQ語句中的以下SQL,這導致了var q2中相當混亂的LINQ。

SELECT COUNT(*) , 'test' FROM [Transcription] 

回答

0

您可以添加一個條件Count

from p in Transcriptions 
where p.WorkflowfolderID == null 
group p by p.TranscriptionStatus.Description into grouped 
select new 
{ 
    xp=grouped.Key, 
    xp1= grouped.Count(), 
    xp2= grouped 
     .Count(p => EntityFunctions.DiffHours(p.DueOn, DateTime.Today) > 0) 
} 

順便說一句,與實體框架也可以使用p.DueOn < DateTime.Today

+0

'計數(謂語)'不是由LINQ到實體的支持。 – MarcinJuraszek 2013-04-24 08:09:59

+0

@MarcinJuraszek。它是(也許不是5.0之前?)。 – 2013-04-24 08:21:56

0

@Gert阿諾德

from p in Transcriptions 
     where p.WorkflowfolderID == null 
     group p by p.TranscriptionStatus.Description into grouped 
     select new 
     { 

     status= (string)grouped.Key, 
     count= grouped.Count(), 
      overdue= grouped.Count(p => p.DueOn < EntityFunctions.AddHours(DateTime.Today, -24)), 


     } 

上面的查詢不工作,我想它。它產生的格式爲

狀態| Count |逾期
----------------------
STATUS1 | 2 | 0
STATUS2 | 1 | 1

是生成的唯一的缺點SQL正在使用內部連接運行2個查詢。我對聯盟的初步想法可能是一個更好的主意,但是您回答了我的問題,並且非常感謝。

可這個查詢在其他一些更清潔的方式比我的上述企圖表示 -

SELECT COUNT(*) , 'test' FROM [Transcription] 
+0

嗨,不客氣。但是,您在這裏的答案部分。我認爲你在這裏寫的不是答案,你最好通過編輯將它添加到原始文章中。如果您的答案對您有幫助,您可能希望將我的答案標記爲已接受您最好將最後一個問題作爲新的StackOverflow問題發佈。 – 2013-04-24 14:07:06

+0

順便說一句,我不明白「2查詢與內部聯接」的意思是喲。我認爲你的意思是在1個較大的查詢中有2個子查詢。數據庫引擎的查詢編譯器應該能夠對其進行優化。 – 2013-04-24 14:08:38

+0

我的意思是生成的查詢和子查詢都有內部聯接。任何方式都已將您的答案標記爲已接受。謝謝 – shai 2013-04-25 01:50:14