sql語句分組排序
① sql多表分組查詢並排序的問題
selectsID,name,timefrom(
selecttb1.sID,tb2.tID,tb3.name,tb3.time
,row_number()over(partitionbytb1.sIDorderbytb3.timedesc)seq
fromtb1a
innerjointb2bona.sID=b.sID
innerjointb3conb.tID=c.tID
)twhereseq=1
② sql 如何分組排序同時進行
1、首先輸入代碼:
SELECT * FROM (select * from CJ where Gender='女') m
where( select COUNT(*) from (select * from CJ where Gender='女') n
where m.Classid = n.Classid and n.English > m.English)<2
order by Classid, English desc
2、然後再輸入代碼:
SELECT * FROM CJ m
where(
select COUNT(*) from CJ n
where m.Classid = n.Classid and n.English > m.English and n.Gender='女')<2 --指的是內表
and Gender='女' --指的是外表
order by Classid, English desc
③ 關於 sql語句 分組 排序查詢 的問題
select 欄位1,欄位2,欄位3,欄位4 from 表
order by 欄位2,欄位4
意思是先用 欄位2 排序,再用 欄位4 排序
④ SQL 分組統計並排序
group
by語句必須和聚合函數一起使用.
select
c,max(d)
from
a
group
by
c
order
by
max(d)
desc
這樣子可以.
因為一條select語句只可以返回一個結果集...
此句返回按c分組後並按每組中最大的d值進行排序.
⑤ SQL分組排序
create
table
#a
(a
char(10),b
int)
insert
#a
select
'a',1
insert
#a
select
'a',5
insert
#a
select
'b',1
insert
#a
select
'b',4
insert
#a
select
'b',3
insert
#a
select
'b',5
create
table
#c
(id
int
identity(1,1),
a
varchar(10))
insert
into
#c
select
distinct
a
from
#A
create
table
#d
(id
int
,
a
varchar(10),b
int)
declare
@a
int
declare
@b
int
select
@a=min(id)
from
#c
select
@b=max(id)
from
#c
while
(@a<=@b)
begin
select
identity(int,1,1)
as
id
,
t1.a,t1.b
into
#b
from
#a
t1,
#c
t2
where
t1.a=t2.a
and
t2.[id]=@a
order
by
t1.b
insert
into
#d
select
*
from
#b
drop
table
#b
set
@a=@a+1
end
select
*
from
#d
⑥ SQL語句中,如果有group by 和order by兩個語句,是先分組還是先排序
先進行分組處理。
Group By 和 Having, Where ,Order by這些關鍵字是按照如下順序進行執行的:Where, Group By, Having, Order by。
首先where將最原始記錄中不滿足條件的記錄刪除(所以應該在where語句中盡量的將不符合條件的記錄篩選掉,這樣可以減少分組的次數)
然後通過Group By關鍵字後面指定的分組條件將篩選得到的視圖進行分組
接著系統根據Having關鍵字後面指定的篩選條件,將分組視圖後不滿足條件的記錄篩選掉
最後按照Order By語句對視圖進行排序,這樣最終的結果就產生了。
在這四個關鍵字中,只有在Order By語句中才可以使用最終視圖的列名,如:
SELECT FruitName, ProctPlace, Price, ID AS IDE, Discount
FROM T_TEST_FRUITINFO
WHERE (ProctPlace = N'china')
ORDER BY IDE
這里只有在ORDER BY語句中才可以使用IDE,其他條件語句中如果需要引用列名則只能使用ID,而不能使用IDE。
⑦ sql語句 在分組內排序
只能用存儲過程
思路如下
將分組那個欄位比如是A
Create temp table tmp_b
foreach
select distinct A into bianlianga from table
insert into tmp_b
select top 2 B from table where A=bianlianga order by B ;
delete from table where A=bianlianga and B in(select * from tmp_b);
end foreach
⑧ 這個SQL語句怎麼寫分組加排序
--效率最高的寫法,比max效率高
select *
from tablename a
where not exists(select 1 from tablename where id = a.id and money > a.money)
order by time
--幾千萬的數據也是not exists效率最好
--最優化的方法是在id列創建聚集索引,然後使用not exists 查詢
⑨ sql語句 按一列分組 然後再按別一列組內排序
sql 按 group 單純的對unitname 分組查詢後 是 "統計數據" ,不存在組內情況,並不會帶有 voucherID,不能排序,對 voucherID 的排序也是無意義。
或者說你按 unitname、voucherID 倆個分組,然後 按voucherID 排序,這個是可以實現的。