当我浏览9gag时随机思考:
他们以下列模式命令他们的帖子(3pic后跟1 gif):
所以我想,他们的表结构可能看起来像这样:
Posts
ID | Title | ContentUrl | Type | UploadedDateTime
1 AAA abc.a Pic 4/10/17 11:54
2 AAB abc.b Gif 4/10/17 11:55
3 AAC abc.c Pic 4/10/17 11:56
4 AAD abc.d Pic 4/10/17 11:57
5 AAE abc.e Gif 4/10/17 11:58
6 AAF abc.f Pic 4/10/17 11:59
7 AAG abc.g Pic 4/10/17 12:00
我可以编写一个sql查询,在不使用游标的情况下返回这样的命令吗?
编辑:我无法相信不知道9gag的人数。
基本上,他们会确保在热门页面中显示gif之间会显示3张图片。所以这种情况下的顺序如下:
5 AAE abc.e Gif 4/10/17 11:58
7 AAG abc.g Pic 4/10/17 12:00
6 AAF abc.f Pic 4/10/17 11:59
4 AAD abc.d Pic 4/10/17 11:57
2 AAB abc.b Gif 4/10/17 11:55
1 AAA abc.a Pic 4/10/17 11:54
3 AAC abc.c Pic 4/10/17 11:56
答案 0 :(得分:1)
MS SQL Server解决方案:
With Posts (ID, Title, ContentUrl, [Type], UploadedDateTime) As (
Select 1, 'AAA', 'abc.a', 'Pic', '4/10/17 11:54' Union All
Select 2, 'AAB', 'abc.b', 'Gif', '4/10/17 11:55' Union All
Select 3, 'AAC', 'abc.c', 'Pic', '4/10/17 11:56' Union All
Select 4, 'AAD', 'abc.d', 'Pic', '4/10/17 11:57' Union All
Select 5, 'AAE', 'abc.e', 'Gif', '4/10/17 11:58' Union All
Select 6, 'AAF', 'abc.f', 'Pic', '4/10/17 11:59' Union All
Select 7, 'AAG', 'abc.g', 'Pic', '4/10/17 12:00'
) Select *,
(ROW_NUMBER() OVER (Partition By [Type] ORDER BY Title) - 1)
* (CASE WHEN [Type] = 'Gif' THEN 3 ELSE 1 END) As _Ordinal
From Posts
Order By _Ordinal, [Type]
ID Title ContentUrl Type UploadedDateTime _Ordinal
2 AAB abc.b Gif 4/10/17 11:55 0
1 AAA abc.a Pic 4/10/17 11:54 0
3 AAC abc.c Pic 4/10/17 11:56 1
4 AAD abc.d Pic 4/10/17 11:57 2
5 AAE abc.e Gif 4/10/17 11:58 3
6 AAF abc.f Pic 4/10/17 11:59 3
7 AAG abc.g Pic 4/10/17 12:00 4
行号Gifs和Pics分别将Gif标准乘以3。
P.S。适合您资源的好广告。 : - )