日期:2014-05-18  浏览次数:20756 次

SQL相同产品相同
years trad_name plsa_revenue
2011 纺织 4200
2011 纺织 4200
2011 纺织 4200
2011 金融 5000
2011 金融 5000
2011 金融 5000
2011 金融 5000
2012 日用化工 3000
2012 日用化工 3000
2012 日用化工 3000



结果:
2011 纺织 18000
2011 金融 20000
2012 日用化工 9000



代码:
select datepart(year,plsa_CreatedDate) as years,
 trad_name,sum(plsa_revenue)as plsa_revenue
  from plsapplication INNER JOIN
  Company 
  on
  plsa_company=Comp_CompanyId INNER JOIN
  trade on 
  comp_trade=trad_tradeID where
  trad_Deleted is null and Comp_Deleted is null and 
  plsa_Deleted is null and datepart(year,plsa_CreatedDate) in (datepart(year,getdate()),year(dateadd(yy,-1,GETDATE())), 
 year(dateadd(yy,-2,GETDATE())))
  group by trad_name,plsa_CreatedDate

------解决方案--------------------
select 
years,
trad_name,
sum( plsa_revenue)
from tb
group by years,
trad_name

??/?
------解决方案--------------------
SQL code

declare @t table 
(years int,trad_name varchar(8),plsa_revenue int)
insert into @t
select 2011,'纺织',4200 union all
select 2011,'纺织',4200 union all
select 2011,'纺织',4200 union all
select 2011,'金融',5000 union all
select 2011,'金融',5000 union all
select 2011,'金融',5000 union all
select 2011,'金融',5000 union all
select 2012,'日用化工',3000 union all
select 2012,'日用化工',3000 union all
select 2012,'日用化工',3000

select years ,trad_name,plsa_revenue=sum(plsa_revenue) from @t 
group by years ,trad_name
/*
years       trad_name plsa_revenue
----------- --------- ------------
2011        纺织        12600
2011        金融        20000
2012        日用化工      9000
*/

------解决方案--------------------
SQL code

create table t1(years int,trad_name varchar(10),plsa_revenue int)
insert  t1
select 2011, '纺织', 4200 union all
select 2011, '纺织', 4200 union all
select 2011, '纺织', 4200 union all
select 2011, '金融', 5000 union all
select 2011, '金融', 5000 union all
select 2011, '金融', 5000 union all
select 2011, '金融', 5000 union all
select 2012, '日用化工', 3000 union all
select 2012, '日用化工', 3000 union all
select 2012, '日用化工', 3000
go
select years,trad_name,SUM(plsa_revenue) as plsa_revenue from t1
group by years,trad_name 
/*
years tra_name   plsa_revenue
----   ------   -----------
2011    纺织    12600
2011    金融    20000
2012    日用化工    9000
*/
go
drop table t1