根据sql server中的列条件进行检查

时间:2015-09-01 15:20:58

标签: sql-server sql-server-2008 sql-server-2005 sql-server-2012

如何在SQL Server中解决此问题

Table: emp 

Pid  | Address           |  City | datetime                   |  Edate       | level
1    | Homeless          |  Chen | 2014-11-13  09:32:14.000   |2013-02-10    |3
1    | 3913 W. Strong    |  Chen | 2011-03-044 19:04:10.000   |2014-02-04    |7
1    | 1100 W MALLON     |  Chen | 2014-11-13  09:32:14.000   |2013-02-10    |5
2    | 610 W GARLAND #3  |  Hyd  | 2013-11-13  09:32:14.000   |2014-04-02    |4
3    | banvanu           |  chen | 2015-03-044 06:04:10.000   |2015-05-06    |6
3    | naneku            |  chen | 2015-03-044 06:04:10.000   |2015-06-09    |4

基于上表我想要输出如下

Pid  | Address           |  City | datetime                   |  Edate       | level
1    | 1100 W MALLON     |  Chen | 2014-11-13  09:32:14.000   |2013-02-10    |5
2    | 610 W GARLAND #3  |  Hyd  | 2013-11-13  09:32:14.000   |2014-04-02    |4
3    | naneku            |  chen | 2015-03-044 06:04:10.000   |2015-06-09    |4

我们需要根据以下条件从同一张表中获取地址,城市

我们得到输出的条件很少:如果max(datetime)值相同,那么第一级检查基于pid的max(datetime)相同的pid需要检查max(edate)如果我们再次得到相同的值然后我们需要检查最大(水平)特定患者的检索地址,该pid的城市

我试过以下

select * from (select *,row_number()over(partition by id ,order by datetime,edate,level)as rno
               from emp)
where rno=1

但是上面的查询未给出预期结果 请告诉我如何在sql server

中编写查询以执行此任务

2 个答案:

答案 0 :(得分:1)

您需要在窗口函数中使用降序:

select [Pid], [Address], [City], [datetime], [Edate], [level]
from (
  select *
       , rn= row_number() over (partition by [pid] 
                                order by [datetime] desc, 
                                         [edate]    desc, 
                                         [level]    desc
                               )
  from emp
) a
where rn = 1;

答案 1 :(得分:0)

试试这个:

WITH Empgroup AS (
    SELECT
        Pid
        , [Address]
        , City
        , [DateTime]
        , EDate
        , [Level]
        , ROW_NUMBER() OVER (PARTITION BY Pid ORDER BY [DateTime] DESC, EDate DESC, [Level] DESC) AS RN
    FROM
        Emp
)
SELECT
    Pid
    , [Address]
    , City
    , [DateTime]
    , EDate
    , [Level]
FROM
    Empgroup
WHERE
    RN = 1

功能差异在于ROW_NUMBER()的排序。然而,我还选择使用公用表表达式来使查询更清晰。