使用SQL MAXDATE拉行

时间:2018-02-06 15:14:13

标签: sql sql-server max greatest-n-per-group

我正在尝试从HR表运行查询。我引入了所有共享相同“Primary_Key_Value”的员工及其家属。我的陈述有效但我得到重复,因为一些家属有多个MED_COV_EFFECTIVE_DATE。我需要引入最新或MAX日期。当我尝试使用MAX(MED_COV_EFFECTIVE_DATE)函数时,我遇到了错误。有人可以帮助我吗?

SELECT DISTINCT PRIMARY_KEY_VALUE, RECORD_ID, LAST_NAME, FIRST_NAME, DATE_OF_BIRTH, HIRE_DATE,
                RELATIONSHIP_CODE, MED_COV_EFFECTIVE_DATE, SOCIAL_SECURITY_NUMBER

FROM COVERAGE_TABLE T1
WHERE T1.PRIMARY_KEY_VALUE IN
(
  SELECT T2.PRIMARY_KEY_VALUE
  FROM COVERAGE_TABLE T2
   WHERE T2.HIRE_DATE IS NOT NULL 

)

ORDER BY PRIMARY_KEY_VALUE, RECORD_ID

3 个答案:

答案 0 :(得分:0)

Dang,没想到内部选择只能提前返回1列。尝试这样的事情:

SELECT T2.PRIMARY_KEY_VALUE, MAX(T2.Med_Cov_Effective_Date)
INTO #MostRecentCoveredKeys
FROM COVERAGE_TABLE T2
WHERE T2.HIRE_DATE IS NOT NULL 
GROUP BY T2.Primary_Key_Value

这应该为您提供一组独特的Primary_Key_Values。

或CTE版本:

; WITH MostRecentCoveredKeys
AS
SELECT T2.PRIMARY_KEY_VALUE, MAX(T2.Med_Cov_Effective_Date)
FROM COVERAGE_TABLE T2
WHERE T2.HIRE_DATE IS NOT NULL 
GROUP BY T2.Primary_Key_Value

然后加入原始表和cte(或临时表),如下所示:

SELECT PRIMARY_KEY_VALUE, RECORD_ID, LAST_NAME, FIRST_NAME, DATE_OF_BIRTH, 
       HIRE_DATE, RELATIONSHIP_CODE, MED_COV_EFFECTIVE_DATE, 
       SOCIAL_SECURITY_NUMBER
FROM COVERAGE_TABLE T1
INNER JOIN MostRecentCoveredKeys mrck
  ON mrck.Primary_Key_Value = T1.Primary_Key_Value
ORDER BY T1.PRIMARY_KEY_VALUE, T1.RECORD_ID

--you need to include the '#' in front of table name 
--on join if using the temp table version
--DROP TABLE #MostRecentCoveredKeys

答案 1 :(得分:0)

此查询将获取最新数据:

SELECT B.PRIMARY_KEY_VALUE, B.RECORD_ID, B.LAST_NAME, B.FIRST_NAME,   
  B.DATE_OF_BIRTH, B.HIRE_DATE, B.RELATIONSHIP_CODE, 
  B.MED_COV_EFFECTIVE_DATE, B.SOCIAL_SECURITY_NUMBER
FROM
(SELECT PRIMARY_KEY_VALUE, MAX(MED_COV_EFFECTIVE_DATE) MAX_DATE
 FROM COVERAGE_TABLE
 WHERE HIRE_DATE IS NOT NULL 
 GROUP BY PRIMARY_KEY_VALUE) A INNER JOIN
(SELECT * FROM COVERAGE_TABLE 
 WHERE HIRE_DATE IS NOT NULL) B
ON A.PRIMARY_KEY_VALUE=B.PRIMARY_KEY_VALUE AND A.MAX_DATE=B.MED_COV_EFFECTIVE_DATE;

答案 2 :(得分:0)

;with a as
(
  select 
    *
    ,row_number() over(partition by PRIMARY_KEY_VALUE, order by Med_Cov_Effective_Date desc) rn
  FROM COVERAGE_TABLE T1
  WHERE HIRE_DATE IS NOT NULL 
)
select *
from a
where rn=1
ORDER BY PRIMARY_KEY_VALUE, RECORD_ID