Data source preparation:
IF OBJECT_ID('TB','u') IS NOT NULL DROP TABLE TB
CREATE TABLE tb(
IDX INT IDENTITY(1,1),
amount int
)
INSERT INTO tb(amount)
VALUEs
(30),(30),(30),(9),(1),(1),(15),(33),(5),(8),(14),(3)
一、前后相减:
SELECT * ,(SELECT a.amount-b.amount from tb b where a.idx=B.idx+1)as cha
from TB a
二、累计求和:
① 表关联
SELECT *,(SELECT SUM(AMOUNT) FROM TB B WHERE B.IDX<=A.IDX)AS HE
FROM TB A
② 窗口函数
select *
,sum(amount) over(order by idx asc ) as HE
from tb
三、多行合并:
select stuff((select ','+cast(amount as varchar) from tb order by amount for xml path('')),1,1,'')
IF OBJECT_ID('TB','U')IS NOT NULL DROP TABLE TB
CREATE TABLE TB(
HOBBY VARCHAR(30)
)
INSERT INTO TB
VALUES ('登山,羽毛球,游泳,瑜伽,翼装飞行')
declare @x xml
SET @x=(select HOBBY=cast('' +replace(HOBBY,',','' )+'' AS xml )
from TB)
select HOBBY=T.c.value('.','varchar(20)')
from @x.nodes('v') T(c)
多行合并补充案例:
现有一张学生选修课程表’TB’,转换成第二张图片的格式
图1:TB表
图2:
Solution:
IF OBJECT_ID('TB','U')IS NOT NULL DROP TABLE TB
CREATE TABLE TB(
NAME VARCHAR(30),
COURSE VARCHAR(30)
)
INSERT INTO TB
VALUES
('张三','Java'),
('李四','拉丁舞'),
('王五','C语言'),
('赵六','Python'),
('张三','R语言'),
('张三','SQL'),
('王五','Tableau')
select name,(select stuff((select ','+course from tb where name=a.name for xml path('') ),1,1,''))as courses
from tb a
GROUP BY name;