【问题标题】:How to remove duplicate records from sql query result after joining multiple tables连接多个表后如何从sql查询结果中删除重复记录
【发布时间】:2018-02-24 17:23:13
【问题描述】:

非常感谢您对以下内容的任何帮助;

使用以下脚本连接多个表以收集我需要的信息后,我现在在结果中有多个重复记录。

我无法使用 distinct,所以在导出之前如何去除 select 语句中的重复结果?

use Cohort

select *

from patients

join immunisations
on patients.patient_id = immunisations.patient_id

join titles
on patients.title_id = titles.title_id

join courses
on immunisations.course_id = courses.course_id

join departments
on patients.patient_id = departments.department_id

join employees
on patients.patient_id = employees.post_title_id

最好的问候

路易丝

【问题讨论】:

  • Distinct 不起作用,因为您使用的是 *.您需要指定要保留的列并再次尝试区分。
  • 在此处发布问题之前,您需要阅读 SQL 基础知识。了解如何使用 GROUP BY 子句:docs.microsoft.com/en-us/sql/t-sql/queries/…
  • 为什么不能使用 distinct?样本数据和预期输出是什么?整行是重复的还是您只关注单个列?
  • @RossBush 当然它会“工作”——如果“工作”是指成功执行。设置不计; cte as (select * from (values (1, 's'), (2, 'b'), (1, 's'), (3, 'z')) as b(id, val)) 选择* 与 cte order by id 不同;鉴于连接和缺少列列表,distinct 在这里是否有用值得怀疑。

标签: sql-server join


【解决方案1】:

@Rossbush @SMor

大家好,你们两个帮我解决了这个问题,我真的很感激。

这就是我所做的工作;

use Cohort

select distinct
    patients.first_name,
    patients.last_name,
    patients.dob,
    titles.description,
    courses.description,
    departments.description,
    immunisations.date_due,
    immunisations.date_given,
    immunisations.comments
from patients
    join immunisations on patients.patient_id = immunisations.patient_id
    join titles on patients.title_id = titles.title_id
    join courses on immunisations.course_id = courses.course_id
    join departments on patients.patient_id = departments.department_id
    join employees on patients.patient_id = employees.post_title_id

非常感谢

路易丝

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多