扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:csdn 来源:csdn 2009年12月18日
关键字: MS-SQL Server 问答
一个sql语句,实现在查询结果中显示每5行后加一空白行
SQL code
exec(
select 1 as jh, ... pivot
union all
select 2 as jh, ... pivot
union all
select 3 as jh, ... pivot
union all
select 4 as jh, ... pivot
union all
select 5 as jh, ... pivot
)
查询结果为:
1 ...
2 ...
3 ...
4 ...
5 ...
1 ...
2 ...
3 ...
4 ...
5 ...
1 ...
2 ...
3 ...
4 ...
5 ...
......
其中这个查询有30列
用
SQL code
union all
select '' as jh ...
30列啊其中还有pivot转化的列
SQL codeCREATE TABLE [TB] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[ITEM] [int] NULL ,
[NOTE] [nvarchar] (20) COLLATE Chinese_PRC_CI_AS NULL ,
CONSTRAINT [PK_TB] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO TB (ITEM, NOTE) SELECT 3,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 3,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 4,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 5,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 5,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 6,'XX'
SELECT * FROM TB
/*-----------------------
3 XX
3 XX
4 XX
5 XX
5 XX
6 XX
*/
SELECT
ITEM=CASE WHEN ID=(
SELECT MIN(ID)
FROM TB
WHERE ITEM=A.ITEM
)
THEN RTRIM(ITEM) ELSE '' END,
NOTE
FROM TB AS A
ORDER BY ID
/*
ITEM NOTE
------------ --------------------
3 XX
XX
4 XX
5 XX
XX
6 XX
SELECT
ITEM,
NOTE
FROM (
SELECT
RTRIM(ITEM) AS ITEM,NOTE,ITEM AS order1,0 AS order2
FROM TB
UNION ALL
SELECT '','',ITEM,1
FROM TB
GROUP BY ITEM
) AS A
ORDER BY order1,order2
3 XX
3 XX
4 XX
5 XX
5 XX
6 XX
SQL codeCREATE TABLE [TB] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[ITEM] [int] NULL ,
[NOTE] [nvarchar] (20) COLLATE Chinese_PRC_CI_AS NULL ,
CONSTRAINT [PK_TB] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO TB (ITEM, NOTE) SELECT 3,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 3,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 4,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 5,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 5,'XX'
INSERT INTO TB (ITEM, NOTE) SELECT 6,'XX'
SELECT * FROM TB
/*-----------------------
3 XX
3 XX
4 XX
5 XX
5 XX
6 XX
*/
SELECT
ITEM=CASE WHEN ID=(
SELECT MIN(ID)
FROM TB
WHERE ITEM=A.ITEM
)
THEN RTRIM(ITEM) ELSE '' END,
NOTE
FROM TB AS A
ORDER BY ID
/*
ITEM NOTE
------------ --------------------
3 XX
XX
4 XX
5 XX
XX
6 XX
SELECT
ITEM,
NOTE
FROM (
SELECT
RTRIM(ITEM) AS ITEM,NOTE,ITEM AS order1,0 AS order2
FROM TB
UNION ALL
SELECT '','',ITEM,1
FROM TB
GROUP BY ITEM
) AS A
ORDER BY order1,order2
3 XX
3 XX
4 XX
5 XX
5 XX
6 XX
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者