2012-10-22 204 views
-3

有人能幫我把這個查詢轉換成linq嗎?我不知道如何使用聯合,然後總結linq。Linq - SQL查詢轉換

SELECT Patientname, SUM(A)AS Trec 
    FROM (SELECT Pm.Patientname, COUNT(*)AS A 
      FROM Facilitycheckinholdorder Fcho 
       INNER JOIN Medordertype Mot ON Fcho.Orderseq = Mot.Orderseq 
       JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq 
        AND Fcho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000' 
        AND Mot.Facilityid = 139 
     GROUP BY Pm.Patientname 
     UNION ALL 
     SELECT Pm.Patientname, COUNT(*)AS A 
     FROM Rxqdeliveryholdorder Rdho 
       INNER JOIN Medordertype Mot ON Rdho.Orderseq = Mot.Orderseq 
       JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq 
        AND Rdho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000' 
        AND Mot.Facilityid = 139 
     GROUP BY Pm.Patientname 
    ) AS Trec 
    GROUP BY Patientname; 

回答

0

事實上,這是不是一個真正的問題,但我已經盡我所能...

var lst1 = 
    from fhco in facilitycheckinholdorder 
    join mot in meordertype on mot.orderseq equals fhco.orderseq 
    join pm in patientmaster on mot.patientseq equals pm.patientseq 
    where 
     fcho.FilledDate >= new DateTime(2011, 9, 1) 
     fcho.FilledDate <= new DateTime(2012, 10, 16) 
    select pm; 
var lst2 = 
    from rdho in rxqdeliveryholdorder 
    join mot in meordertype on rdho.orderseq equals mot.orderseq 
    join pm in patientmaster on moit.patientseq equals pm.patientseq 
    where 
     fcho.FilledDate >= new DateTime(2011, 9, 1) 
     fcho.FilledDate <= new DateTime(2012, 10, 16) 
    select pm; 
var res = 
    from item in lst1.Union(lst2) 
    select new { Name = item.patientname, Count = lst1.Count() + lst2.Count() }; 
0

要點:

  • 你最外面的查詢似乎是多餘的。
  • 你的名字並不常見C#風格,這使得它們很難閱讀。
  • UNION ALL對應於Concat而不是Union
  • 儘早取得Concat可讓您簡化查詢。你可以在SQL中做到這一點。

var result = 
    from order in Queryable.Concat(
     FacilityCheckInHoldOrder.Select(o => new { o.OrderSeq, o.FilledDate }), 
     RxqDeliveryHoldOrder .Select(o => new { o.OrderSeq, o.FilledDate })) 
    where order.FilledDate >= new DateTime(2011, 9, 1) && 
      order.FilledDate < new DateTime(2012, 10, 16) 
    join type in MedOrderType.Where(t => t.FacilityID == 139) 
     on order.OrderSeq equals type.OrderSeq 
    join patient in PatientMaster 
     on type.PatientSeq equals patient.PatientSeq 
    group by patient.PatientName into grp 
    select new 
    { 
     PatientName = grp.Key, 
     Trec = grp.Count() 
    };