You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django在SQL Server下基于report_id的去重查询问题

嘿,这个问题我之前帮朋友解决过,刚好适配SQL Server + Django的场景,给你几个可行的方案:

方案1:利用分组聚合实现去重(最直接)

因为你需要保留report_id和report_name_sc,且同一个report_id对应的report_name_sc应该是一致的,我们可以通过按这两个字段分组,搭配一个无关的聚合函数(比如Max/Min)来触发SQL的分组逻辑,从而实现去重:

from django.db.models import Max

# 按report_id和report_name_sc分组,用report_access的最大值做聚合(只是触发分组,实际值没用)
currreportaccess = QvReportList.objects.filter(report_id__in=reportIds)
                        .values('report_id', 'report_name_sc')
                        .annotate(_unused=Max('report_access'))
                        .order_by('report_id')

这样返回的结果里,每个report_id只会出现一次,同时保留对应的report_name_sc,完全兼容SQL Server。

方案2:先拿唯一ID再查详情(逻辑更直观)

如果report_id和report_name_sc是一一对应的关系,你可以分两步走:先获取去重后的report_id列表,再用这些ID查询对应的名称字段:

# 第一步:拿到所有不重复的report_id
unique_report_ids = QvReportList.objects.filter(report_id__in=reportIds)
                        .values_list('report_id', flat=True)
                        .distinct()

# 第二步:用唯一ID查询需要的两个字段
currreportaccess = QvReportList.objects.filter(report_id__in=unique_report_ids)
                        .values('report_id', 'report_name_sc')
                        .distinct()  # 这里的distinct可以省略,因为report_id已经唯一了

这个方法逻辑简单易懂,适合字段对应关系明确的场景。

方案3:按优先级筛选特定记录(如果需要指定保留哪条)

如果同一个report_id下的report_name_sc可能不同,或者你想优先保留report_access为SUMMARY的记录,可以用子查询来精准筛选:

from django.db.models import Subquery, OuterRef, Case, When, Value, IntegerField

# 子查询:找到每个report_id下优先级最高的记录ID(SUMMARY优先级>Patient)
priority_subquery = QvReportList.objects.filter(report_id=OuterRef('report_id'))
                        .annotate(
                            priority=Case(
                                When(report_access='SUMMARY', then=Value(1)),
                                When(report_access='Patient', then=Value(2)),
                                default=Value(3),
                                output_field=IntegerField()
                            )
                        )
                        .order_by('priority')
                        .values('id')[:1]

# 主查询:只取子查询返回的高优先级记录
currreportaccess = QvReportList.objects.filter(id__in=Subquery(priority_subquery))
                        .values('report_id', 'report_name_sc')

这个方案能确保你拿到的是符合业务优先级的唯一记录,灵活性更高。

内容的提问来源于stack exchange,提问作者user1470034

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:11:55