使用另一个表

时间:2016-07-15 10:05:02

标签: sql sql-server

我正在使用MS SQL。我想用另一个表中的数据更新表中的特定行。我创建了一个查询,它将获取我想要更新的特定行。请注意,我使用了一个选择查询来选择需要更新的特定行。另请注意,有一个子查询用于获取正确的行。对我来说,这使得很难将其纳入集合陈述中。

select tbl1.assessmentcode,  tbl1.Overview from subjectassessmentareas tbl1
inner join  
(   
select assessmentcode,MIN(areaseq) as minassessarea from subjectassessmentareas
where resultgroup = 'PR_Yr8_2' and ResultType = 'KUS_5' 
group by AssessmentCode
) tbl2
on tbl1.AssessmentCode = tbl2.AssessmentCode and tbl1.AreaSeq = tbl2.minassessarea
where fileyear = 2016 and filesemester = 3

这给了我

enter image description here

现在我想用另一个表中的数据更新overview列。这个选择查询为我提供了我想用来更新另一个表的信息。

SELECT AssessmentCode, Overview
FROM SubjectAssessments
WHERE (ClassCampus = 'S') 
    and (FileYear = 2015)   
    and (FileSemester = 3) 
    and filetype = 'A' 
    and AssessmentCode like '08%'

这给了我

enter image description here

有人可以帮助我使用语法来更新上面第一个查询中获得的行中的概述列,并使用第二个查询中包含的概述列,其中Query1.AssessmentCode = Query2.AssessmentCode来自两个查询。

如何使用set语句,然后使用上面的第一个查询来说明要设置哪一行?其他类似的问题只是使用一个简单的集合,然后是一个没有任何where语句的字段。

2 个答案:

答案 0 :(得分:1)

请尝试以下操作:

;WITH cteBaseInfo AS
(
    SELECT AssessmentCode, Overview
    FROM SubjectAssessments
    WHERE (ClassCampus = 'S') 
        and (FileYear = 2015)   
        and (FileSemester = 3) 
        and filetype = 'A' 
        and AssessmentCode like '08%'
)

, cteToBeUpdated AS
(
    select tbl1.assessmentcode,  tbl1.Overview from subjectassessmentareas tbl1
    inner join  
    (   
        select assessmentcode,MIN(areaseq) as minassessarea from subjectassessmentareas
        where resultgroup = 'PR_Yr8_2' and ResultType = 'KUS_5' 
        group by AssessmentCode
    ) tbl2
    on tbl1.AssessmentCode = tbl2.AssessmentCode and tbl1.AreaSeq = tbl2.minassessarea
    where fileyear = 2016 and filesemester = 3.
)

UPDATE  subjectassessmentareas
SET     Overview = (SELECT Overview FROM cteBaseInfo WHERE AssessmentCode = subjectassessmentareas.AssessmentCode)
WHERE   AssessmentCode IN (SELECT AssessmentCode FROM cteToBeUpdated)

请注意,此处AssessmentCode应为主键。

答案 1 :(得分:1)

只需在可更新的CTE中加入这两个:

;with x as (
    select tbl1.assessmentcode,  tbl1.Overview 
    from subjectassessmentareas tbl1
    inner join  
    (   
    select assessmentcode,MIN(areaseq) as minassessarea from subjectassessmentareas
    where resultgroup = 'PR_Yr8_2' and ResultType = 'KUS_5' 
    group by AssessmentCode
    ) tbl2
    on tbl1.AssessmentCode = tbl2.AssessmentCode and tbl1.AreaSeq = tbl2.minassessarea
    where fileyear = 2016 and filesemester = 3
),
y as (
    SELECT AssessmentCode, Overview
    FROM SubjectAssessments
    WHERE (ClassCampus = 'S') 
        and (FileYear = 2015)   
        and (FileSemester = 3) 
        and filetype = 'A' 
        and AssessmentCode like '08%'
),
z as (
    select x.Overview as dest, y.Overview as src
    from x join y on x.AssessmentCode = y.AssessmentCode
)
update z set dest = src