ITPUB第一届“盛拓传媒杯”SQL数据库编程大赛第一期正式开始
这个出的题目,
在5X5的方格棋盘中(如图),每行、列、斜线(斜线不仅仅包括对角线)最多可以放两个球,如何摆放才能放置最多的球,这样的摆法总共有几种?输出所有的摆法。要求:用一句SQL实现。输出格式:从方格棋盘第一行至第5行,每行从第一列到第5列依次输出,0表示不放球,1表示放球。例如:1001000000000000000000000。一行输出一个行号和一个解,按解所在的列字符串顺序从大到小排序。下面是我写的一个sql来完成的
with temp1 as(select case when first_data =1 or second_data =1 then 1 else 0 end fd_1,case when first_data =2 or second_data =2 then 1 else 0 end fd_2,case when first_data =3 or second_data =3 then 1 else 0 end fd_3, case when first_data =4 or second_data =4 then 1 else 0 end fd_4,case when first_data =5 or second_data =5 then 1 else 0 end fd_5 from (select mod(rownum,5) first_data,floor((rownum-1)/5)+1 second_data from dualconnect by rownum<=25)where second_data>first_dataunion allselect 0,0,0,0,0 from dual),temp2 as(select a1.fd_1 fd_1_1,a1.fd_2 fd_1_2,a1.fd_3 fd_1_3,a1.fd_4 fd_1_4,a1.fd_5 fd_1_5,a2.fd_1 fd_2_1,a2.fd_2 fd_2_2,a2.fd_3 fd_2_3,a2.fd_4 fd_2_4,a2.fd_5 fd_2_5,a3.fd_1 fd_3_1,a3.fd_2 fd_3_2,a3.fd_3 fd_3_3,a3.fd_4 fd_3_4,a3.fd_5 fd_3_5,a4.fd_1 fd_4_1,a4.fd_2 fd_4_2,a4.fd_3 fd_4_3,a4.fd_4 fd_4_4,a4.fd_5 fd_4_5,a5.fd_1 fd_5_1,a5.fd_2 fd_5_2,a5.fd_3 fd_5_3,a5.fd_4 fd_5_4,a5.fd_5 fd_5_5from temp1 a1,temp1 a2,temp1 a3,temp1 a4,temp1 a5),temp3 as(select t.*,rownum my_rn ,fd_1_1+fd_1_2+fd_1_3+fd_1_4+fd_1_5+fd_2_1+fd_2_2+fd_2_3+fd_2_4+fd_2_5+fd_3_1+fd_3_2+fd_3_3+fd_3_4+fd_3_5+fd_4_1+fd_4_2+fd_4_3+fd_4_4+fd_4_5+fd_5_1+fd_5_2+fd_5_3+fd_5_4+fd_5_5 my_countfrom temp2 twhere (fd_1_1+fd_2_1+fd_3_1+fd_4_1+fd_5_1)<=2and (fd_1_2+fd_2_2+fd_3_2+fd_4_2+fd_5_2)<=2and (fd_1_3+fd_2_3+fd_3_3+fd_4_3+fd_5_3)<=2and (fd_1_4+fd_2_4+fd_3_4+fd_4_4+fd_5_4)<=2and (fd_1_5+fd_2_5+fd_3_5+fd_4_5+fd_5_5)<=2and (fd_3_1+fd_2_2+fd_1_3)<=2and (fd_5_3+fd_4_4+fd_3_5)<=2and (fd_4_1+fd_3_2+fd_2_3+fd_1_4)<=2and (fd_5_2+fd_4_3+fd_3_4+fd_2_5)<=2and (fd_5_1+fd_4_2+fd_3_3+fd_2_4+fd_1_5)<=2and (fd_1_3+fd_2_4+fd_3_5)<=2and (fd_3_1+fd_4_2+fd_5_3)<=2and (fd_2_1+fd_3_2+fd_4_3+fd_5_4)<=2and (fd_1_2+fd_2_3+fd_3_4+fd_4_5)<=2and (fd_1_1+fd_2_2+fd_3_3+fd_4_4+fd_5_5)<=2)select * from temp3where my_count in( select max(my_count) from temp3)