选择每个ID和部门代码的最新状态

时间:2018-07-16 15:35:32

标签: sql sql-server

我有下表:

enter image description here

我想获取CL_ID具有的每个dept_code的最新状态。因此所需的输出将是这样:

enter image description here

我尝试了以下方法,但这仅给了我每个客户的最新状态,而不是每个客户的dept_codes。

SELECT *
FROM [CIMSHR6_MERGED].[dbo].[C3CLSTAT] C
INNER JOIN
    (SELECT CLIENT_NUMBER, MAX(STATUS_DATE) AS SDATE
    FROM [CIMSHR6_MERGED].[dbo].[C3CLSTAT]
    GROUP BY CLIENT_NUMBER) X
ON X.CLIENT_NUMBER = C.CLIENT_NUMBER
AND X.SDATE = C.STATUS_DATE
ORDER BY C.CLIENT_NUMBER

任何帮助将不胜感激。谢谢。

4 个答案:

答案 0 :(得分:1)

在SQL Server中工作的便捷方法是:

select top (1) cl.*
from [CIMSHR6_MERGED].[dbo].[C3CLSTAT] cl
order by row_number() over (partition by cl_id, dept_code order by status_date desc);

在几乎所有数据库中使用正确索引的有效方法是:

select cl.*
from [CIMSHR6_MERGED].[dbo].[C3CLSTAT] cl
where cl.status_date = (select max(cl2.status_date)
                        from [CIMSHR6_MERGED].[dbo].[C3CLSTAT] cl2
                        where cl2.cl_id = cl.cl_id and cl2.dept_code = cl.dept_code
                       );

正确的索引位于(cl_id, dept_code, status_date)上。

答案 1 :(得分:0)

我也将使用ROW_NUMBER,但使用子查询:

SELECT CL_ID, Status_date, Status, Dept_code
FROM
(
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY CL_ID, Dept_code ORDER BY Status_date DESC) rn
    FROM CIMSHR6_MERGED].[dbo].[C3CLSTAT]
) t
WHERE rn = 1;

答案 2 :(得分:0)

1) Firstly group everything on Dept_Code,CL_ID and assign rank for each row with in the group in descending order.
2) Select all the rows with rnk=1 which would display your desired result. 

    SELECT Z.CL_ID,
           Z.Status_Date,
           Z.Status,
           Z.Dept_Code
      FROM 
         (
             SELECT *,
                    RANK() OVER( PARTITION BY Dept_Code,CL_ID, ORDER BY Status_Date DESC ) AS rnk
               FROM [CIMSHR6_MERGED].[dbo].[C3CLSTAT]
          ) Z
       WHERE Z.rnk = 1;

答案 3 :(得分:0)

这几乎适用于所有数据库

select * from c3clstat c
where exists
(select 1 from c3clstat c1
  where c1.cl_id=c.cl_id
  and c1.dept_code=c.dept_code
group by cl_id,dept_code
having c.status_date=max(c1.status_date)
)