读书人

SQL相同产品相同解决方法

发布时间: 2012-03-27 13:44:24 作者: rapoo

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 

读书人网 >SQL Server

热点推荐