如何写这个查询语句!求救!!!

hitmonkey 2003-12-08 10:57:32
现在我要做一个查询统计,要求统计某个物品的在一段时间内的各种状态,比如说:表中的结构为
historyID,ItemName,ItemStatus,RecordTime(录入时间)。其中ItemStatus是预定义的物品状态,要求查询每一种状态在一段时间内出现的次数。各位大虾,帮帮小弟!
...全文
73 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2003-12-08
  • 打赏
  • 举报
回复
--2.如果是横表的统计,就要用动态SQL语句.
declare @s varchar(8000)
set @s=''
select @s=@s+',['+ItemStatus+']=sum(case ItemStatus when '''
+ItemStatus+''' then 1 else 0 end)'
from(select distinct ItemStatus from 表) a
set @s=substring(@s,2,8000)
exec('select '+@s+' from 表')
go

--为方便调用,可以做成存储过程
create proc p_qry
as
set nocount on
declare @s varchar(8000)
set @s=''
select @s=@s+',['+ItemStatus+']=sum(case ItemStatus when '''
+ItemStatus+''' then 1 else 0 end)'
from(select distinct ItemStatus from 表) a
set @s=substring(@s,2,8000)
exec('select '+@s+' from 表')
set nocount off
go

--调用
exec p_qry

/*--横表指下面的形式
状态1 状态2 状态3
10 1 4
--*/
zjcxc 元老 2003-12-08
  • 打赏
  • 举报
回复
--1.如果是纵表的统计,就用:
select ItemStatus,次数=count(*) from 表 group by ItemStatus

--为方便绑定,可以做成视图:
create view 视图名
as
select ItemStatus,次数=count(*) from 表 group by ItemStatus


/*--纵表指形如下面的形式
ItemStatus 次数
状态1 10
状态2 1
--*/
hitmonkey 2003-12-08
  • 打赏
  • 举报
回复
对了,还要绑定,因为我要打印报表
windofsun 2003-12-08
  • 打赏
  • 举报
回复
select ItemStatus, count(ItemStatus) from table1
group by ItemStatus, datepart(week, RecordTime)
hitmonkey 2003-12-08
  • 打赏
  • 举报
回复
可是状态不是唯一的,是很多种,我要求每一种状态都一一列出来,并统计
realgz 2003-12-08
  • 打赏
  • 举报
回复
select ItemStatus,count(*) as cnt from table
where RecordTime……
group by ItemStatus
zarge 2003-12-08
  • 打赏
  • 举报
回复
对于某个物品
select ItemName, ItemStatus, count(*) as 次数 from 表 where RecordTime Between @begintime and @endtime and Itemname = @ItemName group by ItemName, ItemStatus
zarge 2003-12-08
  • 打赏
  • 举报
回复
select ItemName, ItemStatus, count(*) as 次数 from 表 where RecordTime Between @begintime and @endtime group by ItemName, ItemStatus
sunshareforever 2003-12-08
  • 打赏
  • 举报
回复
select itemname,itemstatus,count(itemstaus) as 次数 from t_table

group by itemname,itemstatus where redordtime between @date1 and @date2

34,874

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧