LINQ分組查詢統計
- 這裏介紹Linq使用Group By和Count得到每個CategoryID中產品的數量,Linq使用Group By和Count得到每個CategoryID中斷貨產品的數量等方面。
學經常會遇到Linq使用Group By問題,這裏將介紹Linq使用Group By問題的解決方法。
1.計數
- var q =
- from p in db.Products
- group p by p.CategoryID into g
- select new {
- g.Key,
- NumProducts = g.Count()
- };
語句描述:Linq使用Group By和Count得到每個CategoryID中產品的數量。
說明:先按CategoryID歸類,取出CategoryID值和各個分類產品的數量。
2.帶條件計數
- var q =
- from p in db.Products
- group p by p.CategoryID into g
- select new {
- g.Key,
- NumProducts = g.Count(p => p.Discontinued)
- };
語句描述:Linq使用Group By和Count得到每個CategoryID中斷貨產品的數量。
說明:先按CategoryID歸類,取出CategoryID值和各個分類產品的斷貨數量。 Count函數裏,使用了Lambda表達式,Lambda表達式中的p,代表這個組裏的一個元素或對象,即某一個產品。
3.Where限制
- var q =
- from p in db.Products
- group p by p.CategoryID into g
- where g.Count() >= 10
- select new {
- g.Key,
- ProductCount = g.Count()
- };
語句描述:根據產品的―ID分組,查詢產品數量大於10的ID和產品數量。這個示例在Group By子句後使用Where子句查找所有至少有10種產品的類別。
說明:在翻譯成SQL語句時,在最外層嵌套了Where條件。
4.多列(Multiple Columns)
- var categories =
- from p in db.Products
- group p by new
- {
- p.CategoryID,
- p.SupplierID
- }
- into g
- select new
- {
- g.Key,
- g
- };
語句描述:Linq使用Group By按CategoryID和SupplierID將產品分組。
說明:既按產品的分類,又按供應商分類。在by後面,new出來一個匿名類。這裏,Key其實質是一個類的對象,Key包含兩個Property:CategoryID、SupplierID。用g.Key.CategoryID可以遍歷CategoryID的值。
5.表達式(Expression)
- var categories =
- from p in db.Products
- group p by new { Criterion = p.UnitPrice > 10 } into g
- select g;
語句描述:Linq使用Group By返回兩個產品序列。第一個序列包含單價大於10的產品。第二個序列包含單價小於或等於10的產品。
說明:按產品單價是否大於10分類。其結果分爲兩類,大於的是一類,小於及等於爲另一類。
6.舉例:
var lst = from p in DC.FWorkBills group p by p.WorkState into g select new {工程狀態=g.Key , 數量=g.Count()}; dataGridGarb2.ItemsSource = lst.ToList(); dataGridGarb2.DataContext = lst.ToList();
7.對比
sql語句-linq語言-lambda表達式對照
1、
查詢Student表中的所有記錄的Sname、Ssex和Class列。
select sname,ssex,class from student
Linq:
from s in Students
select new {
s.SNAME,
s.SSEX,
s.CLASS
}
Lambda:
Students.Select( s => new {
SNAME = s.SNAME,SSEX = s.SSEX,CLASS = s.CLASS
})
2、
查詢教師所有的單位即不重複的Depart列。
select distinct depart from teacher
Linq:
from t in Teachers.Distinct()
select t.DEPART
Lambda:
Teachers.Distinct().Select( t => t.DEPART)
3、
查詢Student表的所有記錄。
select * from student
Linq:
from s in Students
select s
Lambda:
Students.Select( s => s)
4、
查詢Score表中成績在60到80之間的所有記錄。
select * from score where degree between 60 and 80
Linq:
from s in Scores
where s.DEGREE >= 60 && s.DEGREE < 80
select s
Lambda:
Scores.Where(
s => (
s.DEGREE >= 60 && s.DEGREE < 80
)
)
5、
查詢Score表中成績爲85,86或88的記錄。
select * from score where degree in (85,86,88)
Linq:
In
from s in Scores
where (
new decimal[]{85,86,88}
).Contains(s.DEGREE)
select s
Lambda:
Scores.Where( s => new Decimal[] {85,86,88}.Contains(s.DEGREE))
Not in
from s in Scores
where !(
new decimal[]{85,86,88}
).Contains(s.DEGREE)
select s
Lambda:
Scores.Where( s => !(new Decimal[]{85,86,88}.Contains(s.DEGREE)))
Any()應用:雙表進行Any時,必須是主鍵爲(String)
CustomerDemographics CustomerTypeID(String)
CustomerCustomerDemos (CustomerID CustomerTypeID) (String)
一個主鍵與二個主建進行Any(或者是一對一關鍵進行Any)
不可,以二個主鍵於與一個主鍵進行Any
from e in CustomerDemographics
where !e.CustomerCustomerDemos.Any()
select e
from c in Categories
where !c.Products.Any()
select c
6、
查詢Student表中"95031"班或性別爲"女"的同學記錄。
select * from student where class ='95031' or ssex= N'女'
Linq:
from s in Students
where s.CLASS == "95031"
|| s.CLASS == "女"
select s
Lambda:
Students.Where(s => ( s.CLASS == "95031" || s.CLASS == "女"))
7、
以Class降序查詢Student表的所有記錄。
select * from student order by Class DESC
Linq:
from s in Students
orderby s.CLASS descending
select s
Lambda:
Students.OrderByDescending(s => s.CLASS)
8、
以Cno升序、Degree降序查詢Score表的所有記錄。
select * from score order by Cno ASC,Degree DESC
Linq:(這裏Cno ASC在linq中要寫在最外面)
from s in Scores
orderby s.DEGREE descending
orderby s.CNO ascending
select s
Lambda:
Scores.OrderByDescending( s => s.DEGREE)
.OrderBy( s => s.CNO)
9、
查詢"95031"班的學生人數。
select count(*) from student where class = '95031'
Linq:
( from s in Students
where s.CLASS == "95031"
select s
).Count()
Lambda:
Students.Where( s => s.CLASS == "95031" )
.Select( s => s)
.Count()
10、查詢Score表中的最高分的學生學號和課程號。
select distinct s.Sno,c.Cno from student as s,course as c ,score as sc
where s.sno=(select sno from score where degree = (select max(degree) from score))
and c.cno = (select cno from score where degree = (select max(degree) from score))
Linq:
(
from s in Students
from c in Courses
from sc in Scores
let maxDegree = (from sss in Scores
select sss.DEGREE
).Max()
let sno = (from ss in Scores
where ss.DEGREE == maxDegree
select ss.SNO).Single().ToString()
let cno = (from ssss in Scores
where ssss.DEGREE == maxDegree
select ssss.CNO).Single().ToString()
where s.SNO == sno && c.CNO == cno
select new {
s.SNO,
c.CNO
}
).Distinct()
操作時問題?執行時報錯: where s.SNO == sno(這行報出來的)
運算符"=="無法應用於"string"和"System.Linq.IQueryable<string>"類型的操作數
解決:
原:let sno = (from ss in Scores
where ss.DEGREE == maxDegree
select ss.SNO).ToString()
Queryable().Single()返回序列的唯一元素;如果該序列並非恰好包含一個元素,則會引發異常。
解:let sno = (from ss in Scores
where ss.DEGREE == maxDegree
select ss.SNO).Single().ToString()
11、查詢'3-105'號課程的平均分。
select avg(degree) from score where cno = '3-105'
Linq:
(
from s in Scores
where s.CNO == "3-105"
select s.DEGREE
).Average()
Lambda:
Scores.Where( s => s.CNO == "3-105")
.Select( s => s.DEGREE)
.Average()
12、查詢Score表中至少有5名學生選修的並以3開頭的課程的平均分數。
select avg(degree) from score where cno like '3%' group by Cno having count(*)>=5
Linq:
from s in Scores
where s.CNO.StartsWith("3")
group s by s.CNO
into cc
where cc.Count() >= 5
select cc.Average( c => c.DEGREE)
Lambda:
Scores.Where( s => s.CNO.StartsWith("3") )
.GroupBy( s => s.CNO )
.Where( cc => ( cc.Count() >= 5) )
.Select( cc => cc.Average( c => c.DEGREE) )
Linq: SqlMethod
like也可以這樣寫:
s.CNO.StartsWith("3") or SqlMethods.Like(s.CNO,"%3")
13、查詢最低分大於70,最高分小於90的Sno列。
select sno from score group by sno having min(degree) > 70 and max(degree) < 90
Linq:
from s in Scores
group s by s.SNO
into ss
where ss.Min(cc => cc.DEGREE) > 70 && ss.Max( cc => cc.DEGREE) < 90
select new
{
sno = ss.Key
}
Lambda:
Scores.GroupBy (s => s.SNO)
.Where (ss => ((ss.Min (cc => cc.DEGREE) > 70) && (ss.Max (cc => cc.DEGREE) < 90)))
.Select ( ss => new {
sno = ss.Key
})
14、查詢所有學生的Sname、Cno和Degree列。
select s.sname,sc.cno,sc.degree from student as s,score as sc where s.sno = sc.sno
Linq:
from s in Students
join sc in Scores
on s.SNO equals sc.SNO
select new
{
s.SNAME,
sc.CNO,
sc.DEGREE
}
Lambda:
Students.Join(Scores, s => s.SNO,
sc => sc.SNO,
(s,sc) => new{
SNAME = s.SNAME,
CNO = sc.CNO,
DEGREE = sc.DEGREE
})
15、查詢所有學生的Sno、Cname和Degree列。
select sc.sno,c.cname,sc.degree from course as c,score as sc where c.cno = sc.cno
Linq:
from c in Courses
join sc in Scores
on c.CNO equals sc.CNO
select new
{
sc.SNO,c.CNAME,sc.DEGREE
}
Lambda:
Courses.Join ( Scores, c => c.CNO,
sc => sc.CNO,
(c, sc) => new
{
SNO = sc.SNO,
CNAME = c.CNAME,
DEGREE = sc.DEGREE
})
16、查詢所有學生的Sname、Cname和Degree列。
select s.sname,c.cname,sc.degree from student as s,course as c,score as sc where s.sno = sc.sno and c.cno = sc.cno
Linq:
from s in Students
from c in Courses
from sc in Scores
where s.SNO == sc.SNO && c.CNO == sc.CNO
select new { s.SNAME,c.CNAME,sc.DEGREE }