sql分組查詢的完整語句
分組查詢 group by 主要是對(count,sum,avg,min,max)
例如
表A
a b c
一 1 2
一 1 3
二 2 5
三 7 7
二 9 9
select a,sum(b),sum(c) from A group by a
對分組數據進行限制
select a,sum(b),sum(c) from A group by a having sum(b)>5
求幾個簡單的SQL單表分組查詢語句
如果最高分不只一個呢。
.. select * from Result where grade=1 and gender='男' and score = (select max(score) from result);select * from Result where grade=1 and score=(select max(score) from Result);select * from Result where gender='女'and score=(select max(score) from Result);select * from Result where score in (select max(score) from Result group by grade);注:grade 年級name 姓名gender 性別score 分數誰用誰知道!。
sql語句分組查詢,按條件分組的問題
select distinct class,(select count(a) from tb where flag=1 and * = *),(select count(a) from tb where flag=2 and * = *),(select count(a) from tb where flag=3 and * = *) from tb t group by class,flag嘿嘿,看看結果吧。
求救SQL分組查詢統計查詢語句
這樣啊,那在取月份的時候加上條件就可以了,另外請注意,4月應該沒有31號,如果轉換成日期/時間比較的話就會出錯
select c.姓名,c.登錄月份,iif(isnull(d.次數),0,d.次數) as 次數
from ((select a.姓名,b.登錄月份 from (select distinct 姓名 from [user]) a,(select distinct format(登錄日期,'yyyy-mm') as 登錄月份 from [user] where format(登錄日期,'yyyy-mm-dd') between '2009-01-01' and '2009-04-30') b) c
left join (select 姓名,format(登錄日期,'yyyy-mm') as 登錄月份, count(*) as 次數 from [User]
where format(登錄日期,'yyyy-mm-dd') between '2009-01-01' and '2009-04-30' group by 姓名,format(登錄日期,'yyyy-mm')) d
on c.姓名 = d.姓名 and c.登錄月份 = d.登錄月份) order by c.登錄月份, c.姓名
----------------------------------------------------
我測試過了,應該沒有問題,需要確認一下的是,你的“登錄日期”字段是“日期/時間”型的嗎?
補充:
對應Access的答案
select c.姓名,c.登錄月份,iif(isnull(d.次數),0,d.次數) as 次數
from ((select a.姓名,b.登錄月份 from (select distinct 姓名 from [user]) a,(select distinct format(登錄日期,"yyyy-mm") as 登錄月份 from [user]) b) c
left join (select 姓名,format(登錄日期,"yyyy-mm") as 登錄月份, count(*) as 次數 from [User]
where format(登錄日期,"yyyy-mm-dd") between '2009-01-01' and '2010-01-31' group by 姓名,format(登錄日期,"yyyy-mm")) d
on c.姓名 = d.姓名 and c.登錄月份 = d.登錄月份)
———————————————————————————————————
樓上的答案日期范圍只能選擇1個月,如果是多個月份的將不能體現每個月的登陸次數。
我寫了一個答案,可以參考一下:
select c.姓名,c.登錄月份,isnull(d.次數,0) as 次數
from ((select a.姓名,b.登錄月份 from (select distinct 姓名 from [user]) a,(select distinct convert(varchar(7),登錄日期,120) as 登錄月份 from [user]) b) c
left join (select 姓名,convert(varchar(7),登錄日期,120) as 登錄月份, count(*) as 次數 from [User]
where convert(varchar(10),登錄日期,120) between '2009-01-01' and '2010-01-31' group by 姓名,convert(varchar(7),登錄日期,120)) d
on c.姓名 = d.姓名 and c.登錄月份 = d.登錄月份)
以上算法依然會存在問題,就是必須登錄日期中存在所有的月份才可以,如果某個月份中所有的用戶等沒有登錄記錄將無法統計到該月份的信息(0次)
如果想要包括唯有登錄記錄的月份信息,則只能通過存儲過程來獲取時間段內的所有月份。
不知樓主明白否?
sql 分類匯總查詢語句
醉含笑的很牛,不過SUM(pay)有點需要改動
最終完美版:
select min(id) as 序號,
max(dept) as 部門,
sum(case when zt='01' OR zt='02' then pay else 0 end) as 合計,
sum(case zt when 01 then 1 else 0 end) as 個數01狀態,
sum(case zt when 02 then 1 else 0 end) as 個數02狀態,
count(zt) as 總數
from aac
group by dept
轉載請注明出處華閱文章網 » sql的分組查詢語句