日期:2014-05-18 浏览次数:20598 次
declare @n int;
set @n=5;
;with cte as
(
select SN,Value,rn=(SN-1)/@n
from tb
),
cte2 as
(
select distinct value=stuff((select ';'+value from cte where c.rn=rn order by SN for xml path('')),1,1,''),c.rn
from cte c
)
select SN=row_number()over(order by rn),value from cte2;
------解决方案--------------------
纸种 规格 重量
仿牛卡 1200*1100 1.1
仿牛卡 1200*1100 1.2
仿牛卡 1200*1100 1.3
仿牛卡 1200*1100 1.4
仿牛卡 1200*1100 1.5
仿牛卡 1200*1100 1.1
仿牛卡 1200*1100 1.2
高瓦 1200*1200 1.3
高瓦 1200*1200 1.3
高瓦 1200*1200 1.3
能不能通过SQL 语句得到以下统计出来的结果:
仿牛卡 1200*1100 1.1 1.2 1.3 1.4 1.5 5件
仿牛卡 1200*1100 1.1 1.2 2件
高瓦 1200*1200 1.3 1.3 1.3 3件
其中第一行与第二行是相等的,只是在打印的时候,如果把第二行都统计到第一行太长了,打印纸打印不下。
把原来的七条拆分成两行,5个记录一行。
------------------------------------
-- Author : HappyFlyStone
-- Date : 2009-10-22
-- Version: Microsoft SQL Server 2005 - 9.00.2047.00 (Intel X86)
-- Apr 14 2006 01:12:25
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Enterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
--
------------------------------------
-- Test Data: ta
IF OBJECT_ID('[ta]') IS NOT NULL
DROP TABLE [ta]
Go
CREATE TABLE ta([纸种] NVARCHAR(3),[规格] NVARCHAR(9),[重量] NUMERIC(2,1))
Go
INSERT INTO ta
SELECT '仿牛卡','1200*1100',1.1 UNION ALL
SELECT '仿牛卡','1200*1100',1.2 UNION ALL
SELECT '仿牛卡','1200*1100',1.3 UNION ALL
SELECT '仿牛卡','1200*1100',1.4 UNION ALL
SELECT '仿牛卡','1200*1100',1.5 UNION ALL
SELECT '仿牛卡','1200*1100',1.1 UNION ALL
SELECT '仿牛卡','1200*1100',1.2 UNION ALL
SELECT '高瓦','1200*1200',1.3 UNION ALL
SELECT '高瓦','1200*1200',1.3 UNION ALL
SELECT '高瓦','1200*1200',1.3
GO
--Start
alter table ta add col int default 0
go
if object_id('F_Str11') is not null
drop function F_Str11
go
create function F_Str11(@Col varchar(10),@col1 int)
returns nvarchar(100)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+ltrim(重量) from ta where 纸种=@Col and col = @col1
return @S
end
go
declare @i int ,@j varchar(10)
set @i = 0
update ta
set col = (@I-1)/5,@I = case when @j <> [纸种] then 1 else @i + 1 end,
@j = [纸种]
select 纸种,规格,dbo.f_str11(纸种,col) from ta
group by 纸种,规格,col
--Result:
/*
纸种 规格
---- --------- ------------------------
仿牛卡 1200*1100 1.1,1.2,1.3,1.4,1.5
仿牛卡 1200*1100 1.1,1.2
高瓦 1200*1200 1.3,1.3,1.3
(3 行受影响)
*/
--End
------解决方案--------------------
declare @n int;
set @n=5;
;with cte as
(
select SN,Value,rn=(SN-1)/@n---这里每5行分成一组了
from tb
),
cte2 as
(
select distinct value=stuff((select ';'+value from cte where c.rn=rn order by SN for xml path('')),1,1,''),c.rn----字符串的合并 用XMML 建议去看看XML语法
from cte c
)
select SN=row_number()over(order by rn),value from cte2;