求SQL语句怎么写
一张单位表Unit:
ID Name
1 中石油
2 中移动
3 电信
另一张表Info:
ID UnitID Num Point
1 1 1 2
2 1 2 1
3 2 1 1
4 3 2 2
若Num=1时 得1分 若Num=2时 得3分
若Point=1时 得1分 若Point=2 得3分
还有在info表中有单位纪录一条得1分
希望得到的表如下
Name 得分
中石油 10
中移动 3
电信 7
例举第一条10分的计算(计算方式(在Info表UnitID为1时有两条加2分,其中Num一个为1一个为2所以加4分,Point一个为2一个为1所以再加4分,总为10分)
)
[解决办法]
- SQL code
select a.name,sum(case when b.num = 1 then 1 when b.num = 2 then 3 else 0 end) + sum(case when b.Point= 1 then 1 when b.Point= 2 then 3 else 0 end) + sum(1) as 得分from unit a,info bwhere b.unitid = a.idgroup by a.name
[解决办法]
- SQL code
select a.name, sum(case when b.num = 1 then 1 when b.num = 2 then 3 else 0 end) + sum(case when b.Point= 1 then 1 when b.Point= 2 then 3 else 0 end) + sum(case when b.unitid is not null then 1 else 0 end) as 得分from unit a left join info bon b.unitid = a.idgroup by a.name
[解决办法]
- SQL code
use Tempdbgo--> --> if not object_id(N'Tempdb..#Unit') is null drop table #UnitGoCreate table #Unit([ID] int,[Name] nvarchar(50))Insert #Unitselect 1,N'中石油' union allselect 2,N'中移动' union allselect 3,N'电信'Goif not object_id(N'Tempdb..#Info') is null drop table #InfoGoCreate table #Info([ID] int,[UnitID] int,[Num] int,[Point] int)Insert #Infoselect 1,1,1,2 union allselect 2,1,2,1 union allselect 3,2,1,1 union allselect 4,3,2,2GoSELECT b.[Name],得分=SUM(CASE WHEN a.[Num]=1 THEN 1 WHEN a.[Num]=2 THEN 3 ELSE 0 END+CASE WHEN a.[Point]=1 THEN 1 WHEN a.[Point]=2 THEN 3 ELSE 0 END)+COUNT(a.[UnitID])FROM #Info AS a RIGHT JOIN #Unit AS b ON b.ID=a.[UnitID] GROUP BY b.[Name]
[解决办法]
- SQL code
select t1.Uname Uname,sum((case when t2.Num=1 then 1 else 3)+count(t2.id)+sum(case when t2.Point=1 then 1 else 2)) '得分' from Unit t1 inner join Info t2 on t1.id=t2.UnitID group by t1.Uname
[解决办法]
- SQL code
select t1.Uname Uname,sum((case when t2.Num=1 then 1 else 3 end)+count(t2.id)+sum(case when t2.Point=1 then 1 else 2 end)) '得分' from Unit t1 inner join Info t2 on t1.id=t2.UnitID group by t1.Uname
[解决办法]
我也不知道