如何用sql语句合并重复的数据

如何用sql语句合并重复的数据,第1张

--这样?
select from 表名 a where not exists(select 1 from 表名 where 开票日期=a开票日期 and 货号=a货号 and 收货人=a收货人 and 序号<a序号)

楼主要实现的是金额动态列吧! 动态列的实现一般可以用两部来实现,第一步拼接group 出SQL,第二步拼接sql,比如楼主的需求可以这样来实现

1: select 'sum (case when 金额 = '' '金额' '' then 金额 else 0 end) ' from 数据表 group by 金额

2: 将上面的结果字符 用程序处理并拼接起来,可以得到,拼接后的结果如下:

select 单号 ,sum (case when 金额 = 金额1 then 金额 else 0 end) as 金额1 ,
sum (case when 金额 = 金额2 then 金额 else 0 end) as 金额2
from 数据表 group by 单号

一、创建表:

create table stuUnion

(

sid int identity primary key,

cid int,

id varchar(500)

)

二、添加数据:

insert into stuUnion

elect 1,'a' union

select 1,'b' union

select 2,'c' union

select 2,'d' union

select 3,'e' union

select 3,'f' union

select 3,'g'

三、用标量函数查询:

创建标量函数:

create function b(@cid int)

returns varchar(500)

as

begin

declare @s varchar(500)

select @s=isnull(@s+'','')+rtrim(id)+',' from stuUnion where cid=@cid

return @s

end;

用标量函数查询:

select cid,dbob(cid) as id from stuUnion group by cid

用sqlserver的xml:

select cid,ID=STUFF((select ' '+rtrim(id)+',' from stuUnion where stcid=cid order by id for XML path('')),1,1,'') from stuUnion st group by cid

select a,b,c from tb1
union (all)�0�2
select d,e,f from tb2
要去除重复的用union,不去除得话用union alld,e,f的数据类型要可以转换成a,b,c

不知道你是用的什么数据库,又是要用什么语言,我给你写个ASP的吧 for i = 1 to 5 sql = "UPDATE [表名] SET [id] = [id" & i & "] WHERE [id] = NULL" connexecute(sql) next 不明白再问 ------------------>> 用我这个笨方法吧复制下面SQL语句到MS SQL 的SQL查询分析器,把表名改为你的表名,运行就OK了 UPDATE [表名] SET [id] = [id1] WHERE [id] = NULL UPDATE [表名] SET [id] = [id2] WHERE [id] = NULL UPDATE [表名] SET [id] = [id3] WHERE [id] = NULL UPDATE [表名] SET [id] = [id4] WHERE [id] = NULL UPDATE [表名] SET [id] = [id5] WHERE [id] = NULL很不错哦

模仿这个代码:
Create
FUNCTION
JoinString
--合并字符串
多行合并为一行(
@UserName
varchar(50)
)
RETURNS
varchar(8000)
AS
BEGIN
declare
@Str
varchar(8000)
set
@Str
=
''
select
@Str
=
@Str
+','
+
ISNull(BuMenName,'')
from
ERPUserGuanliDept
where
UserName
=
@UserName
if(@Str<>'')
set
@Str=substring(@Str,2,len(@Str)-1)
return
@Str
END
使用时
select
distinct
UserName,dboJoinString(UserName)
as
DeptList
from
ERPUserLingdaoDept


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/yw/13409475.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-07-30
下一篇 2023-07-30

发表评论

登录后才能评论

评论列表(0条)

保存