从多个日期中选择最长日期

时间:2016-10-13 02:39:01

标签: sql sql-server tsql

这是我的情况:

我有两张桌子SKU& Disco_Dates

在两个表中都有类似的字段。

SKU.[MFG_PART_NUMBER] = Disco_Dates.[MATERIAL]

我需要知道每个MFG_PART_NUMBER的最大DATE_UPDATE

DISCO_DATE TABLE

+-------------+-----------------------+-----------------------+
| MATERIAL    |DISCO_DATE             | DATE_UPDATE           | 
+-------------+-----------------------+-----------------------+
|T6C25AW#ABC  |NULL                   |2016-09-14 11:15:03.587|
|T6C25AW#ABC  |2016-10-28 00:00:00.000|2016-09-21 13:45:03.591| 
|T6C25AW#ABC  |2016-10-31 00:00:00.000|2016-09-30 12:38:08.990| 
+-------------+-----------------------+-----------------------+

SKU TABLE

+---------------+
|MFG_PART_NUMBER| 
+---------------+
|T6C25AW#ABC    |
|G2F32UC#ABC    |
+---------------+

SQL QUERY

SELECT
 t1.[MFG_PART_NUMBER]
,t2.[DISCO_DATE]
,MAX (t2.[DATE_UPDATE]) as DATE_UPDATE

FROM Test.dbo.SKU t1

LEFT JOIN Test.dbo.Tbl_Disco_Dates t2
ON [MFG_PART_NUMBER] = [MATERIAL]

WHERE t1.[MFG_PART_NUMBER] = 'T6C25AW#ABC'

group by 
  t1.[MFG_PART_NUMBER]
 ,t2.[DISCO_DATE]

我目前的结果是给了我所有3行。

这就是我需要的。

+----------------+-----------------------+-----------------------+
|MFG_PART_NUMBER |DISCO_DATE             | DATE_UPDATE           |  
+----------------+-----------------------+-----------------------+
|T6C25AW#ABC     |2016-10-31 00:00:00.000|2016-09-30 12:38:08.990| 
+----------------+-----------------------+-----------------------+

提前致谢。

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
 t1.[MFG_PART_NUMBER]
,t2.[DISCO_DATE]
,t2.[DATE_UPDATE] as DATE_UPDATE

FROM Test.dbo.SKU t1

LEFT JOIN Test.dbo.Tbl_Disco_Dates t2
ON [MFG_PART_NUMBER] = [MATERIAL]

WHERE t1.[MFG_PART_NUMBER] = 'T6C25AW#ABC'
      AND t2.[DATE_UPDATE] = (SELECT MAX(t2.[DATE_UPDATE] FROM Test.dbo.Tbl_Disco_Dates t2)

答案 1 :(得分:2)

 declare @maxdate datetime
 select @maxdate = max(t2.[DATE_UPDATE]) FROM Test.dbo.SKU
 select * from ( SELECT
  t1.[MFG_PART_NUMBER]
 ,t2.[DISCO_DATE]
  , DATE_UPDATE

  FROM Test.dbo.SKU  where DATE_UPDATE=   @maxdate)   t1 
  LEFT JOIN Test.dbo.Tbl_Disco_Dates t2
   ON t1.[MFG_PART_NUMBER] = t2.[MATERIAL]

  WHERE t1.[MFG_PART_NUMBER] = 'T6C25AW#ABC'

  group by 
 t1.[MFG_PART_NUMBER]
 ,t2.[DISCO_DATE]

答案 2 :(得分:1)

不会进行简单的GROUP BY查询工作:

SELECT MATERIAL,
       MAX(DISCO_DATE) AS DISCO_DATE,
       MAX(DATE_UPDATE) AS DATE_UPDATE
FROM Test.dbo.Tbl_Disco_Dates
GROUP BY MATERIAL