原数据库中的表结构如下所示:
如图所示,所有的数据都显示在这一行里面,我需要将其显示成多数据行并且按照点击次数降序排列。
我是这样处理的:
CREATE FUNCTION FUNC_NEWTABLE()
RETURNS @TMP_TABLE TABLE
(
TITLE VARCHAR(100), --标题
LINKURL VARCHAR(200), --链接地址
[COUNT] INT --统计数
)
AS
BEGIN
INSERT INTO @TMP_TABLE(TITLE,LINKURL,[COUNT])
SELECT title1,link1,count1 from hotarticle
union all
SELECT title2,link2,count2 from hotarticle
union all
SELECT title3,link3,count3 from hotarticle
union all
SELECT title4,link4,count4 from hotarticle
union all
SELECT title5,link5,count5 from hotarticle
union all
SELECT title6,link6,count6 from hotarticle
union all
SELECT title7,link7,count7 from hotarticle
union all
SELECT title8,link8,count8 from hotarticle
union all
SELECT title9,link9,count9 from hotarticle
union all
SELECT title10,link10,count10 from hotarticle
RETURN
END
GO
Select * from dbo.FUNC_NEWTABLE() order by [count] desc
RETURNS @TMP_TABLE TABLE
(
TITLE VARCHAR(100), --标题
LINKURL VARCHAR(200), --链接地址
[COUNT] INT --统计数
)
AS
BEGIN
INSERT INTO @TMP_TABLE(TITLE,LINKURL,[COUNT])
SELECT title1,link1,count1 from hotarticle
union all
SELECT title2,link2,count2 from hotarticle
union all
SELECT title3,link3,count3 from hotarticle
union all
SELECT title4,link4,count4 from hotarticle
union all
SELECT title5,link5,count5 from hotarticle
union all
SELECT title6,link6,count6 from hotarticle
union all
SELECT title7,link7,count7 from hotarticle
union all
SELECT title8,link8,count8 from hotarticle
union all
SELECT title9,link9,count9 from hotarticle
union all
SELECT title10,link10,count10 from hotarticle
RETURN
END
GO
Select * from dbo.FUNC_NEWTABLE() order by [count] desc
主要就是利用sql函数将数据存储在一个新的表结构中,然后从新的表结构中提取数据。原理比较简单,得到的信息显示如下: