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关键字的.