SQL Server-如何从多个表中获取每个组的最新更新

时间:2019-06-14 07:36:48

标签: sql sql-server

例如,我有3个表:

tbl_main
-------------------------
|ID_No |Info1   |Info2  |
|------+--------+-------|
|00123 |name1   |a city |
|00567 |name2   |b city |
|00789 |name3   |c city |
-------------------------

tbl_version
--------------------------------
|ID_No |Version_Name|Version_No|
|------+------------+----------|
|00123 |version_a_01|1         |
|00567 |version_b_01|1         |
|00789 |version_c_01|1         |
--------------------------------

tbl_version_upd
--------------------------------
|ID_No |Version_Name|Version_No|
|------+------------+----------|
|00123 |version_a_02|2         |
|00123 |version_a_03|2         |
|00123 |version_a_04|4         |
|00789 |version_c_02|2         |
--------------------------------

我想从tbl_version和tbl_version_upd的组合中基于Version_No获取每个ID_No的最新Version_Name。

Wanted output:
--------------------------------------
|ID_No |Info1   |Info2  |Version_Name|
|------+--------+-------+------------|
|00123 |name1   |a city |version_a_04|
|00567 |name2   |b city |version_b_01|
|00789 |name3   |c city |version_c_02|
--------------------------------------

当前,我有以下查询:

Select a.ID_No, a.Info1, a.Info2, b.Version_Name
FROM tbl_main a
LEFT JOIN (tbl_version UNION ALL tbl_version_upd) b ON a.ID_No=b.ID_No

但是它获取每个ID_No的所有版本

Current output:
--------------------------------------
|ID_No |Info1   |Info2  |Version_Name|
|------+--------+-------+------------|
|00123 |name1   |a city |version_a_01|
|00123 |name1   |a city |version_a_02|
|00123 |name1   |a city |version_a_03|
|00123 |name1   |a city |version_a_04|
|00567 |name2   |b city |version_b_01|
|00789 |name3   |c city |version_c_01|
|00789 |name3   |c city |version_c_02|
--------------------------------------

2 个答案:

答案 0 :(得分:2)

应用是获得它的好方法,我也为联合使用了CTE,但仅出于可读性考虑,子查询也能正常工作

;WITH allversions AS (
    SELECT ID_No, Version_Name, Version_No
    FROM tbl_version
    UNION ALL 
    SELECT ID_No, Version_Name, Version_No
    FROM tbl_version_upd
)
SELECT a.ID_No, a.Info1, a.Info2, b.Version_Name
FROM tbl_main a
OUTER APPLY (
    SELECT TOP 1 Version_Name 
    FROM allversions av
    WHERE av.ID_No = a.ID_No
    ORDER BY Version_No DESC
) b

答案 1 :(得分:0)

您可以在下面使用相关子查询尝试

Select a.ID_No, a.Info1, a.Info2, b.Version_Name
FROM tbl_main a
LEFT JOIN (tbl_version UNION ALL tbl_version_upd) b ON a.ID_No=b.ID_No
where version_no in 
      (select max(version_no) from (tbl_version UNION ALL tbl_version_upd) b1 
           where b.ID_No=b1.ID_No)