首页 新闻 会员 周边

sql 统计查询 分页的问题

0
悬赏园豆:50 [已解决问题] 解决于 2016-03-06 15:53

如表A
id name bid cid  time

1   jerry   1     1   2015-11-09
2   tom    1     1   2015-11-08
3   lucy    2     1   2015-11-07
4   tom    1     1   2015-11-08
5   lucy    3     1   2015-11-07

表B
bid   name
1     状态1
2     状态2
3     状态3

表C
cid  name
1     公司1


结果
公司,         时间,           状态1,    状态2,    状态3
公司1     2015-11-07         0                1               1
公司1     2015-11-08         2                0               0
公司1     2015-11-09         1                0               0

请问SQL语句该怎么写?需要进行分页,谢谢!

御寒宵的主页 御寒宵 | 初学一级 | 园豆:111
提问于:2015-11-19 15:31
< >
分享
最佳答案
0

-- 给一段SQLServer 2005+ 下的代码

-- 设置每页条数和取第几页
declare @pagesize int, @pagenum int
set @pagesize = 20
set @pagenum = 1


select C.name as [公司], t.time, t.[状态1], t.[状态2], t.[状态3]
from
(
    select
    cid,
    time,
    sum(case bid when 1 then 1 else 0 end) as [状态1],
    sum(case bid when 2 then 1 else 0 end) as [状态2],
    sum(case bid when 3 then 1 else 0 end) as [状态3],
    row_number() over (order by cid, time) as [rank]
    from A group by cid, time
)t inner join C
on t.rank between (@pagenum-1)*@pagesize +1  and @pagenum*@pagesize and t.cid = C.cid

收获园豆:20
脚本王子 | 小虾三级 |园豆:779 | 2015-12-29 11:44
其他回答(3)
0

先写个视图,然后对视图进行分页就行了。

收获园豆:10
Firen | 园豆:5385 (大侠五级) | 2015-11-19 15:56
0

int strPage=(pageIndex-1)*pageSize;

int endPage=pageIndex*pageSize;

select top 20 * from 

(

select row_number() over(order by a.排序的列 desc)rownum,* from 表名 a

)temp where temp.rownum>=starPage and temp<=endPage

这个是MVC的三层架构,传入pageIndex和pageSize

收获园豆:10
如此低调的男人 | 园豆:842 (小虾三级) | 2015-11-19 16:25

get it

 

支持(0) 反对(0) 小刺猬001 | 园豆:660 (小虾三级) | 2015-11-30 14:51
0

结果中列的个数应该不是固定的 真的可以写成视图么?

单单现在这样的行转列,就不是简单一个sql可以实现的吧。。

写了一个sql,但只是【状态1,状态2,状态3】部分实际是需要拼接sql才可行的。。

SELECT * FROM (
SELECT #C.name AS 公司,#A.time AS 时间,#B.NAME FROM #A,#B,#C
where #A.bid = #B.bid AND #A.cid=#C.cid)X
PIVOT(COUNT(name) FOR name IN (状态1,状态2,状态3))a

因为涉及到拼接sql和分页,我推荐用存储过程来做。

不过也许是在下才疏学浅,没能想到好的办法。期待大牛的回答。。

收获园豆:10
小白菜T | 园豆:564 (小虾三级) | 2015-11-19 20:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册