select row_number() over (order by insu_admdvs) as '序号', insu_admdvs '医保区划', count(distinct mdtrt_id,psn_no)'结算人次', sum(medfee_sumamt) '医疗总费用', sum(fund_pay_sumamt) '基金支出' from setl_d where vali_flag = '1' group by insu_admdvs 的错误
时间: 2023-08-05 10:08:43 浏览: 182
这段 SQL 语句存在语法错误,应该将 "count(distinct mdtrt_id,psn_no)" 改为 "count(distinct mdtrt_id, psn_no)",即在逗号后面加上一个空格。修改后的正确语句如下:
```
select row_number() over (order by insu_admdvs) as '序号', insu_admdvs '医保区划', count(distinct mdtrt_id, psn_no) '结算人次', sum(medfee_sumamt) '医疗总费用', sum(fund_pay_sumamt) '基金支出' from setl_d where vali_flag = '1' group by insu_admdvs
```
相关问题
怎么优化下面SQL: select distinct bid from ( select row_number() over(order by bid,start_date) as num,bid,start_date,end_date from t1 )a inner join ( select row_number() over(order by bid,start_date) as num,bid,start_date,end_date from t1 )b on a.bid = b.bid where a.num = b.num+1
可以考虑使用CTE(公共表表达式)来优化该SQL语句。具体做法如下:
```
WITH cte AS (
SELECT ROW_NUMBER() OVER (ORDER BY bid, start_date) AS num, bid, start_date, end_date
FROM t1
)
SELECT DISTINCT a.bid
FROM cte a
INNER JOIN cte b ON a.bid = b.bid AND a.num = b.num + 1
```
使用公共表表达式的好处是可以避免重复计算,使得SQL语句更加简洁和易于理解。在这个例子中,我们只需要计算一次ROW_NUMBER()函数,然后在CTE中引用它即可。同时,使用WITH语句也可以使得SQL语句更加可读性强,更加易于维护。
with temp as ( select tname,card_id,scores,open_id,inserttime, count(1) over(partition by open_id) as card_cnt, row_number() over(partition by open_id order by inserttime) as card_asc, row_number() over(partition by open_id order by scores desc,inserttime desc) as card_desc from text1 where open_id in ( select open_id from text1 group by open_id having count(distinct card_id)>1 ) ),temp_a as ( select * from temp where card_cnt > 1 and card_asc=1 ),temp_b as ( select * from temp where card_cnt > 1 and card_desc=1 ) select a.tname as 姓名,b.scores as 考核最高分 from temp_a a left join temp_b b on a.open_id = b.open_id; 解题思路
这个SQL查询的目标是找出在表text1中有多张卡片的用户中,每个用户的第一张卡片和最后一张卡片的姓名和考核最高分。
首先,使用子查询temp找出所有有多张卡片的用户,并为每个用户的每张卡片计算出以下信息:
- tname: 姓名
- card_id: 卡片ID
- scores: 考核分数
- open_id: 用户ID
- inserttime: 插入时间
- card_cnt: 用户拥有的卡片数量
- card_asc: 卡片按插入时间升序排列的序号
- card_desc: 卡片按考核分数降序和插入时间降序排列的序号
接下来,使用子查询temp_a找出每个用户的第一张卡片,条件为card_cnt大于1且card_asc为1。
然后,使用子查询temp_b找出每个用户的最后一张卡片,条件为card_cnt大于1且card_desc为1。
最后,通过左连接将temp_a和temp_b连接起来,并选择姓名和考核最高分作为结果。
请注意,这只是一个解题思路,并没有完整的代码,实际使用时可能需要根据具体数据库类型和表结构进行调整。
阅读全文