22,210
社区成员
发帖
与我相关
我的任务
分享
ID city count level
1 北京市 50
2 北京市 20
3 北京市 10
4 邯郸市 20
5 邯郸市 10
6 邯郸市 80
update tbl03
set levels = (case
when ((T1.counts*100.0)/T2.sumc) > 80 then '高'
when (((T1.counts*100.0)/T2.sumc <= 80) and ((T1.counts*100)/T2.sumc > 60)) then '中'
when ((T1.counts*100.0)/T2.sumc) <= 60 then '低'
end)
from tbl03 AS T1
left join
(select city, sum(counts) as sumc from tbl03 group by city) AS T2
ON T1.city = T2.city
create table #tb
(
ID int,
city varchar(20),
[count] int,
[level] varchar(20)
)
insert into #tb (ID,city,[count])
select 1,'北京市',50 union all
select 2,'北京市',20 union all
select 3,'北京市',10 union all
select 4,'邯郸市',20 union all
select 5,'邯郸市',10 union all
select 6,'邯郸市',80
;with cte as
(
select a.ID,
a.city,
a.[count],
case
WHEN 1.0*a.[count]/b.sumcount>0.8 THEN '高'
WHEN 1.0*a.[count]/b.sumcount>0.6 and 1.0*a.[count]/b.sumcount<0.8 THEN '中'
WHEN 1.0*a.[count]/b.sumcount<0.6 THEN '低'
END as [level]
from #tb a
inner join(
select city,SUM([count]) as sumcount
from #tb
group by city
) b on a.city=b.city
)
update #tb set [level]=cte.[level] from cte where cte.ID=#tb.ID
select * from #tb
ID city count level
----------- -------------------- ----------- --------------------
1 北京市 50 中
2 北京市 20 低
3 北京市 10 低
4 邯郸市 20 低
5 邯郸市 10 低
6 邯郸市 80 中
(6 行受影响)
CREATE TABLE #temp(ID int, city nvarchar(3),[count] int, [level] nvarchar(1))
INSERT INTO #temp(ID,city,[count])
SELECT 1,N'北京市',50 UNION ALL
SELECT 2,N'北京市',20 UNION ALL
SELECT 3,N'北京市',10 UNION ALL
SELECT 4,N'邯郸市',20 UNION ALL
SELECT 5,N'邯郸市',10 UNION ALL
SELECT 6,N'邯郸市',80
-- 这里开始创建为存储过程
;WITH s AS (
SELECT city,
SUM([count]) total
FROM #temp
GROUP BY city
)
UPDATE #temp
SET #temp.[level] = (CASE WHEN #temp.[count] >= (s.total*80/100) THEN
N'高'
WHEN #temp.[count] >= (s.total*60/100) THEN
N'中'
ELSE
N'低'
END)
FROM #temp, s
WHERE #temp.city = s.city
--存储过程结束
SELECT * FROM #temp
ID city count level
----------- ------ ----------- -----
1 北京市 50 中
2 北京市 20 低
3 北京市 10 低
4 邯郸市 20 低
5 邯郸市 10 低
6 邯郸市 80 中