/*
在5X5的方格棋盘中,每行,列,斜线(斜线不仅仅包括对角线)最多可以放两个球,如何摆放才能放置最多的球,这样的摆法总共有几种?输出所有的摆法.
要求:用一句SQL实现
输出格式:从方格棋盘第一行至第5行,每行从第一列到第5列依次输出,0表示不放球,1表示放球.一行输出一个行号和一个解
例如:
行号,结果
1 0001101001110000011010100
2 0001101010100011010001100
3 0001101100100010011011000
*/
WITH ct
AS
(
SELECT v,
CONVERT(INT,SUBSTRING(v,1,1)) AS a,
CONVERT(INT,SUBSTRING(v,2,1)) AS b,
CONVERT(INT,SUBSTRING(v,3,1)) AS c,
CONVERT(INT,SUBSTRING(v,4,1)) AS d,
CONVERT(INT,SUBSTRING(v,5,1)) AS e
FROM
(
SELECT STUFF(v,b.number,1,'1') AS v
FROM
(
SELECT STUFF('00000',number,1,'1') AS v
FROM master.dbo.spt_values WHERE type='P' AND number BETWEEN 1 AND 5
) a
CROSS JOIN
(
SELECT number FROM master.dbo.spt_values WHERE type='P' AND number BETWEEN 1 AND 5
) b
GROUP BY STUFF(v , b.number , 1 , '1')
) c
)
SELECT ROW_NUMBER() OVER(ORDER BY v) AS r,v FROM
(
SELECT
a.v+b.v+c.v+d.v+e.v AS v,
RANK() OVER(ORDER BY LEN(REPLACE(a.v+b.v+c.v+d.v+e.v,'1','')) ) AS id
FROM ct a CROSS JOIN ct b CROSS JOIN ct c CROSS JOIN ct d CROSS JOIN ct e
WHERE
a.a+a.b+a.c+a.d+a.e<=2 AND
b.a+b.b+b.c+b.d+b.e<=2 AND
c.a+c.b+c.c+c.d+c.e<=2 AND
d.a+d.b+d.c+d.d+d.e<=2 AND
e.a+e.b+e.c+e.d+e.e<=2 AND
a.a+b.a+c.a+d.a+e.a<=2 AND
a.b+b.b+c.b+d.b+e.b<=2 AND
a.c+b.c+c.c+d.c+e.c<=2 AND
a.d+b.d+c.d+d.d+e.d<=2 AND
a.e+b.e+c.e+d.e+e.e<=2 AND
a.b+b.a<=2 AND
a.c+b.b+c.a<=2 AND
a.d+b.c+c.b+d.a<=2 AND
a.e+b.d+c.c+d.b+e.a<=2 AND
b.e+c.d+d.c+e.b<=2 AND
c.e+d.d+e.c<=2 AND
d.e+e.d<=2 AND
a.d+b.e<=2 AND
a.c+b.d+c.e<=2 AND
a.b+b.c+c.d+d.e<=2 AND
a.a+b.b+c.c+d.d+e.e<=2 AND
b.a+c.b+d.c+e.d<=2 AND
c.a+d.b+e.c<=2 AND
d.a+e.b<=2
) y
WHERE id=1