如何简化我的代码

时间:2013-11-30 19:15:41

标签: group-by subquery union

我被要求每个月显示一个月前N个计数记录的信息,我的意思是,我需要计算一个字段,选择前5个并与每个月/年绑定。我目前的代码如下:

( 
select calle1, count(calle1), year(fecha_registro), MONTH(fecha_registro) from dbo_accidentes1 
where year(fecha_registro)=2013 and MONTH(fecha_registro)=1 
GROUP BY calle1 
order by count(calle1) desc LIMIT 6 
) 
UNION 
( 
select calle1, count(calle1), year(fecha_registro), MONTH(fecha_registro) from dbo_accidentes1 
where year(fecha_registro)=2013 and MONTH(fecha_registro)=2 
GROUP BY calle1 
order by count(calle1) desc LIMIT 6 
) 
UNION 
( 
select calle1, count(calle1), year(fecha_registro), MONTH(fecha_registro) from dbo_accidentes1 
where year(fecha_registro)=2013 and MONTH(fecha_registro)=3 
GROUP BY calle1 
order by count(calle1) desc LIMIT 6 
) 
UNION 
( 
select calle1, count(calle1), year(fecha_registro), MONTH(fecha_registro) from dbo_accidentes1 
where year(fecha_registro)=2013 and MONTH(fecha_registro)=4 
GROUP BY calle1 
order by count(calle1) desc LIMIT 6 
) 
UNION 
( 
select calle1, count(calle1), year(fecha_registro), MONTH(fecha_registro) from dbo_accidentes1 
where year(fecha_registro)=2013 and MONTH(fecha_registro)=5 
GROUP BY calle1 
order by count(calle1) desc LIMIT 6 
) 
UNION 
( 
select calle1, count(calle1), year(fecha_registro), MONTH(fecha_registro) from dbo_accidentes1 
where year(fecha_registro)=2013 and MONTH(fecha_registro)=6 
GROUP BY calle1 
order by count(calle1) desc LIMIT 6 
) 

它显示了一些像这样的东西:

https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-prn2/q71/s720x720/1468653_659639267414302_124224845_n.jpg

代码很大,但工作正常。我想知道是否有任何方法可以减少它,因为我认为我将来会与其他几个月合作。我尝试了很多连接,子查询,但它们都没有为我工作,我无法从内部查询或连接中的第二个表中检索前5条记录。

1 个答案:

答案 0 :(得分:0)

尝试这个,以防你的RDBMS支持窗口函数:

with t as 
(select calle1, count(calle1) as count_acc, year(fecha_registro) as year_acc, MONTH(fecha_registro) as Month_acc 
from dbo_accidentes1 
GROUP BY calle1, year(fecha_registro),MONTH(fecha_registro) ), 
t2 as
(select  calle1, count_acc, year_acc, Month_acc,
ROW_NUMBER() OVER (PARTITION BY calle1 ORDER BY count_acc desc) as rank)
select *
from t2
where rank <= 6