当前位置: 代码迷 >> Sql Server >> SQL相同产品相同解决方法
  详细解决方案

SQL相同产品相同解决方法

热度:78   发布时间:2016-04-27 14:33:56.0
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 @tselect 2011,'纺织',4200 union allselect 2011,'纺织',4200 union allselect 2011,'纺织',4200 union allselect 2011,'金融',5000 union allselect 2011,'金融',5000 union allselect 2011,'金融',5000 union allselect 2011,'金融',5000 union allselect 2012,'日用化工',3000 union allselect 2012,'日用化工',3000 union allselect 2012,'日用化工',3000select years ,trad_name,plsa_revenue=sum(plsa_revenue) from @t group by years ,trad_name/*years       trad_name plsa_revenue----------- --------- ------------2011        纺织        126002011        金融        200002012        日用化工      9000*/
------解决方案--------------------
SQL code
create table t1(years int,trad_name varchar(10),plsa_revenue int)insert  t1select 2011, '纺织', 4200 union allselect 2011, '纺织', 4200 union allselect 2011, '纺织', 4200 union allselect 2011, '金融', 5000 union allselect 2011, '金融', 5000 union allselect 2011, '金融', 5000 union allselect 2011, '金融', 5000 union allselect 2012, '日用化工', 3000 union allselect 2012, '日用化工', 3000 union allselect 2012, '日用化工', 3000goselect years,trad_name,SUM(plsa_revenue) as plsa_revenue from t1group by years,trad_name /*years tra_name   plsa_revenue----   ------   -----------2011    纺织    126002011    金融    200002012    日用化工    9000*/godrop table t1
  相关解决方案