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

求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 b
where b.unitid = a.id
group 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 b
on
 b.unitid = a.id
group by
 a.name

------解决方案--------------------
SQL code
use Tempdb
go
--> --> 
 
if not object_id(N'Tempdb..#Unit') is null
    drop table #Unit
Go
Create table #Unit([ID] int,[Name] nvarchar(50))
Insert #Unit
select 1,N'中石油' union all
select 2,N'中移动' union all
select 3,N'电信'
Go

if not object_id(N'Tempdb..#Info') is null
    drop table #Info
Go
Create table #Info([ID] int,[UnitID] int,[Num] int,[Point] int)
Insert #Info
select 1,1,1,2 union all
select 2,1,2,1 union all
select 3,2,1,1 union all
select 4,3,2,2
Go


SELECT 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

------解决方案--------------------
我也不知道