暂无图片
求一SQL
我来答
分享
chengang
2023-04-07
求一SQL
with cte as ( select 1 as id,100 as total union all select 1 as id,100 as total union all select 2 as id,100 as total union all select 3 as id,33 as total ) select sum(total) from cte
复制

上述结果为333
但我实际想要的结果为233 当id重复的时候 取一行数据就可以了。

我有复杂的实现算法,但由于业务SQL很复杂,不能适用

贴一下复杂的解决方案供交流

with cte as ( select 1 as id,100 as total union all select 1 as id,100 as total union all select 2 as id,100 as total union all select 3 as id,33 as total ), cte1 as ( select @id,case when id = @id then 0 else total end as calctotal, @id:= id from cte,(select @id := -1) as rr ) select sum(calctotal) from cte1;
复制

这样操作后结果就为233.

我来答
添加附件
收藏
分享
问题补充
4条回答
默认
最新
不期而遇

with cte as
(select 1 as id, 100 as total
from dual
union all
select 1 as id, 100 as total
from dual
union all
select 2 as id, 100 as total
from dual
union all
select 3 as id, 33 as total from dual)
select sum(tmp.total)
from (select id,
total,
row_number() over(partition by id order by id) as line
from cte) tmp
where tmp.line = 1
试试这个

暂无图片 评论
暂无图片 有用 0
打赏 0
暂无图片
刘贵宾

这样试试呢

WITH cte AS (
  SELECT DISTINCT id, total 
  FROM (
    SELECT 1 AS id, 100 AS total UNION ALL
    SELECT 1 AS id, 100 AS total UNION ALL
    SELECT 2 AS id, 100 AS total UNION ALL
    SELECT 3 AS id, 33 AS total
  ) t
)
SELECT SUM(total) FROM cte;
复制
暂无图片 评论
暂无图片 有用 3
打赏 0
chengang
题主
2023-04-07
这个方法不行。我那个重复行的结果集,还有其它列,不能这样使用。
刘晓华

按Id分组排序取第一行的记录求和

select  sum(total) 

from  (

            select row_number() over(partition by id order by total) as rn, total

            from  cte

            where rn = 1

          )

暂无图片 评论
暂无图片 有用 0
打赏 0
刘晓华

你这个是SQL SERVER里的,思路一样的,换成SQL SERVER就可以了

暂无图片 评论
暂无图片 有用 0
打赏 0
不期而遇
2023-04-07
oracle和mysql都支持的
不期而遇
2023-04-07
试过了
回答交流
Markdown


请输入正文
提交
问题信息
请登录之后查看
邀请回答
暂无人订阅该标签,敬请期待~~
暂无图片墨值悬赏