A. 有一張表存儲了用戶獲得各種禮物的數量,如果我要查詢出各種禮物獲得最多的用戶,sql應該怎樣寫謝謝
----建立表結構:
create table tableTest
(
id int identity(1,1) primary key,
name nvarchar(50),
type nvarchar(50),
num int
)
insert into tableTest values('a','花',10);
insert into tableTest values('b','煙',50);
insert into tableTest values('c','酒',13);
insert into tableTest values('d','花',18);
insert into tableTest values('e','煙',20);
insert into tableTest values('f','糖',11);
insert into tableTest values('a','糖',11);
----具體執行代碼如下:
create table #table1
(
name varchar(255),
type varchar(255),
num int
)
create table #table2
(
num int,
type varchar(255)
)
create table #table3
(
name varchar(255),
type varchar(255),
num int
)
declare @name varchar(255)
declare @number int
declare @type varchar(255)
declare se_type cursor for
select distinct type from tableTest
open se_type
fetch se_type into @type
while(@@fetch_status=0)
begin
insert into #table1 select name,type,sum(num) from tableTest group by type,name having type=@type
insert into #table2 select max(num),type from #table1 group by type having type=@type
insert into #table3 select #table1.name,#table1.type,#table1.num from #table1 inner join #table2 on #table1.num=#table2.num and #table1.type=#table2.type where #table1.type=@type
fetch se_type into @type
end
close se_type
deallocate se_type
select * from #table3
完全按照你的要求去做的,希望能幫助到你。如有更簡便方法,望討論交流!
B. sql server 2005 查找並統計前10名數量最多的用戶
例表tab_test ,數量列名:sl
selecttop10*fromtab_testorderbyddesc
語句執行,先將結果集按 sl 的降序 排序,然後使用 top 10 選擇前10行數據。
如果單一用戶有多條記錄,那需要將用戶分組,計算數量
例表tab_test ,數量列名:sl,用戶列名: user
selecttop10user,sum(sl)as'sl_xj'fromtab_test
groupbyuserorderbysl_xjdesc
C. sql查找一列數據中數量最多的
看你是查找前2名的數據,所以應該這樣寫
select top 2 * from 表名
order by sl desc
D. sql 怎實現查詢數據表內出現最多次數的數據
selectdate_format(addtime,'%Y%m%d'),count(date_format(addtime,'%Y%m%d'))fromtb_Parkinginformatiwhere
addtimeBETWEEN'2015-05-0100:00:00'AND'2015-07-0200:00:00'
groupbydate_format(addtime,'%Y%m%d');
不知道你使用的資料庫是什麼類型的,這里提供MYSQL的查詢方法,供你參考一下(盲寫的SQL,可能有一點錯誤,但是大致的方法就是這樣了)
E. sql查詢出現最多的數據
sql查詢出現最多的數據 1
使用count函數即可。
例如:
表名test
id name
1 a
1 b
1 f
2 c
2 d
3 e
F. sql如何查出總數量的最大數
select top 1 cName , sum(iQuantity) as 總數量 from table1 group by cName order by 總數量 desc
G. sql 如何取總數的最大值
select top 1 客戶
from (
select 客戶,總數=SUM(數量)
from tablea
) k
order by 總數 desc
H. sql 查詢每個存貨編碼的「數量」列出現最多的一項,並統計佔比
create table temp as
select 編碼,數量,rank()over(order by 數量 desc) as rn
from table_01
where 數量 is not null
;
select distinct
編碼,
數量,
出現最多的次數 ,
出現最多的次數 /總數量 as 佔比
from
(select 編碼,
數量,
sum(rn) as 出現最多的次數
from temp
where rn = 1
group by 編碼, 數量)a
left join
(select 編碼,
max(rn) as 總數量
from temp
group by 編碼
) b on a.編碼 = b.編碼
類似這樣的 ,代碼沒調試,主要在於用rank按照數量降序排列;
I. SQL如何實現 每月最大人數 及最少人數統計
SelectTop1*
From(
select日期,count(ID),sum(工作量)FROM表WHERE(時間區間)groupbyrqorderbysum(工作量)desc
)a
這個是獲取人數最多的,將子查詢中的desc去掉或者改為asc,可以查詢最少的.
另外,這個是sql server的語法,Oracle不支持top關鍵字的.