2013-10-17 58 views
0

嘗試將以下SQL查詢轉換爲LINQ,但我堅持由ClientCompany進行分組。LINQ中的分組和MIN()

SELECT TOP 300 ClientCompany, 
CASE WHEN MIN(FeatureID) = 12 THEN 1 ELSE 0 END as Sort 
FROM Ad 
LEFT JOIN AdFeature 
ON Ad.ID = AdFeature.AdID 
WHERE (AdFeature.FeatureID = 13 OR AdFeature.FeatureID = 12) 
AND SiteID = 2 
GROUP BY ClientCompany 
ORDER BY Sort DESC 

我嘗試將其轉換爲LINQ:

(from a in Ads 
join af in AdFeatures 
on new { 
join1 = a.ID, 
join3 = 2 
} equals new { 
join1 = af.AdID, 
join3 = af.SiteID 
} 
let sort = (
af.FeatureID == 12 ? 1 : 0 
) 
orderby sort descending 
where af.FeatureID == 13 || af.FeatureID == 12 
select new { a.ClientCompany, sort }).Take(300) 

我將如何使用MIN(FeatureID)GROUP BY ClientCompany在LINQ,所以我只有每ClientCompany得到單列回來?

編輯

這個工作!根據Daniel Hilgarth的回答。這個解決方案有什麼可怕的錯誤嗎?

Ads.Join(AdFeatures, x => x.ID, x => x.AdID, 
(a, af) => new { Ad = a, AdFeature = af }) 
.Where(x => x.AdFeature.FeatureID == 12 || x.AdFeature.FeatureID == 13) 
.Where(x => x.AdFeature.SiteID == 2) 
.GroupBy(x => x.Ad.ClientCompany) 
.Select(g => new { ClientCompany = g.Key, Sort = g.Min(x => x.AdFeature.FeatureID) == 12 ? 1 : 0 }) 
.OrderByDescending(x => x.Sort) 
.Take(300) 

回答

4

試試這個:

Ads.Join(AdFeatures, x => x.FeatureID, x => x.FeatureID, 
     (a, af) => new { Ad = a, AdFeature = af }) 
    .Where(x => x.AdFeature.FeatureID == 12 || x.AdFeature.FeatureID == 13) 
    .Where(x => x.AdFeature.SiteID == 2) 
    .GroupBy(x => x.Ad.ClientCompany) 
    .Select(g => new { ClientCompany = g.Key, 
         Sort = g.Min(x => x.AdFeature.FeatureID) == 12 ? 1 : 0 }); 

請注意,我改變了左外連接到內部聯接,因爲你原來的查詢訪問AdFeature無條件,使其成爲一個內部聯接。

+0

所有答案都包含我不習慣的lambda表達式。你能解釋一下這裏發生了什麼嗎? 當我用LINQPad 4試用時,它不工作。 _'LINQPad.User.Ad'不包含'Fea​​tureID'的定義,也沒有接受'LINQPad'類型的第一個參數的擴展方法'FeatureID' .User.Ad'可以找到(按F4添加使用指令或程序集引用)_ –

+1

使用了一些修改(在原始文章中更新)。謝謝! –

0

試試這個:

(from a in ads 
join af in AdFeatures on a.ID equals af.AdID into g 
from x in g.DefaultIfEmpty() 
where x.FeatureID == 13 || x.FeatureID == 12 
where x.SiteID == 2 
orderby a.Sort descending 
group a by a.ClientCompany into g2 
from x2 in g2 
let sort = g2.Select(T => T.FeatureID).Min() == 12 ? 1 : 0 
select new { a.ClientCompany, Sort = sort }).Take(300); 

爲什麼需要分組呢?

+0

分組是爲了獲得每個公司的最小值。你的查詢得到全局的最小值,所以它甚至可能爲0. –

0

您好我會寫這樣的

  context.Ads.Where(ad => ad.AdFeatures.Any(feature => (feature.FeatureID == 13 || feature.FeatureID == 12) && feature.SiteID == 2)) 
        .GroupBy(ad => ad.ClientCompany) 
        .Select(ads => new 
        { 
         cc = ads.Key, sort = ads.SelectMany(ad => ad.AdFeatures) 
               .Select(feature => feature.FeatureID) 
               .Min() == 12 
        }) 
        .OrderBy(arg => arg.sort).Take(300);