create table tb( 公司名称 varchar(10),统计日期 datetime,金额 int,产品 char(10))insert into tb
select 'A公司', '2010-7-1', 100,'a' union all
select 'A公司', '2010-7-2', 200,'b' union all
select 'A公司', '2010-7-3', 200,'b' union all
select 'A公司', '2010-8-2', 200,'a' union all
select 'B公司', '2011-1-1', 300,'c'
select 公司名称,convert(varchar(7),统计日期,120) as 日期,sum(金额) as 金额,
产品=stuff((select ','+产品 from tb where 公司名称=a.公司名称 and convert(varchar(7),统计日期,120)= convert(varchar(7),a.统计日期,120) for xml path('')),1,1,'')
from tb a group by 公司名称,convert(varchar(7),统计日期,120)查询结果
公司 日期 金额 产品
A公司 2010-07 500 a ,b ,b
A公司 2010-08 200 a
B公司 2011-01 300 c 这边我想实现产品如有重复则去掉重复的以及tb表发生更新就把该表数据插入tb2表应该怎么修改。另外当公司名称不存在时则不导入tb2
-- 1、加distinct
select 公司名称,convert(varchar(7),统计日期,120) as 日期,sum(金额) as 金额,
产品=stuff((select distinct ','+产品 from tb where 公司名称=a.公司名称 and convert(varchar(7),统计日期,120)= convert(varchar(7),a.统计日期,120) for xml path('')),1,1,'')
from tb a group by 公司名称,convert(varchar(7),统计日期,120)
create table tb(公司名称 varchar(10),统计日期 datetime,金额 int,产品 varchar(10))insert into tb
select 'A公司', '2010-7-1', 100,'a' union all
select 'A公司', '2010-7-2', 200,'b' union all
select 'A公司', '2010-7-3', 200,'b' union all
select 'A公司', '2010-8-2', 200,'a' union all
select 'B公司', '2011-1-1', 300,'c'
select 公司名称,convert(varchar(7),统计日期,120) as 日期,sum(金额) as 金额,
产品=stuff((select distinct ','+产品 from tb where 公司名称=a.公司名称 and convert(varchar(7),统计日期,120)= convert(varchar(7),a.统计日期,120) for xml path('')),1,1,'')
from tb a group by 公司名称,convert(varchar(7),统计日期,120)--tb表更新数据放入tb2表
create table tb2(公司名称 varchar(10),统计日期 datetime,金额 int,产品 varchar(10))
gocreate trigger tb_insert on tb
for update
as
begin
insert into tb2 select * from inserted where [公司名称] is not null
end
goupdate tb
set 金额 = 200
where 公司名称 = 'A公司' and 产品 = 'a'select * from tb2drop trigger tb_insert
drop table tb,tb2公司名称 日期 金额 产品
---------- ------- ----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
A公司 2010-07 500 a,b
A公司 2010-08 200 a
B公司 2011-01 300 c公司名称 统计日期 金额 产品
---------- ----------------------- ----------- ----------
A公司 2010-08-02 00:00:00.000 200 a
A公司 2010-07-01 00:00:00.000 200 a