跨两个或更多查询的SQL MAX()值

时间:2014-08-06 15:25:27

标签: sql max

这似乎是SQL中的一个基本操作,但它让我感到难过。

我有大约2个不同的子查询,每个子查询按LOCATION_ID分组,包含日期列。例如,一个查询包括WORKORDER个记录的列表,而另一个查询从NOTE表中提取记录。这两个查询都包含LOCATION表的联接,允许我按LOCATION_ID进行分组。

我的目标是在该特定位置提取最新联系日期,并且可以采用存储在不同表格中的工作单,备注日期,后续日期等形式。理想情况下,我会按LOCATION_ID分组查询,显示该位置的最新联系日期。

我会发布SQL但我没有任何目前正在为我工​​作的东西。关于如何处理这种情况的任何想法?

谢谢!

SELECT 
   L.LOCATION_ID, Max(MaxDate) 
FROM 
   LOCATION AS L
LEFT JOIN 
   (SELECT 
       LOCATION_ID, Max(dbo.LeadNote.NoteDate) AS MaxDate 
    FROM 
       LeadNote 
    INNER JOIN 
       LOCATION ON LeadNote.LOCATION_ID = LOCATION.LOCATION_ID 
    GROUP BY 
       LOCATION_ID) T1 ON L.LOCATION_ID = T1.CONTACTLOCATION_LOCATION_ID
LEFT JOIN 
   (SELECT 
       LOCATION_ID, Max(dbo.WORKORDER.WORKORDER_DATECREATED) AS MaxDate 
    FROM 
       WORKORDER 
    INNER JOIN 
       LOCATION ON LOCATION_ID = WORKORDER_LOCATION_ID 
    GROUP BY 
       LOCATION_ID) T2 ON L.LOCATION_ID = T2.CONTACTLOCATION_LOCATION_ID`

4 个答案:

答案 0 :(得分:1)

也许您可以尝试使用UNION获取单个sql结果,然后将其包装并为其赋予别名,然后在您希望的字段上应用MAX,两个查询都返回。请记住,要使用UNION,两个查询都必须返回相同的字段名称集。

例如:

Query A:

   Select a, b, c from T1 where....

Query B:
   Select a, f, e from T2 where...


you would have:

  SELECT MAX(e)
  FROM
    ( 
     (Select a, b, c, NULL as f, NULL as e from T1 where....)
     UNION
     (Select a, NULL as b, NULL as c, f, e from T2 where...)
    ) t

答案 1 :(得分:0)

如果您需要使用连接,可以使用case语句来获取更大的日期。

SELECT
   L.LOCATION_ID,
   (CASE WHEN(T2.MaxDate IS NULL OR T1.MaxDate > T2.MaxDate)
   THEN T1.MaxDate
   ELSE T2.MaxDate
   END) MaxDate
...

答案 2 :(得分:0)

尝试:

SELECT 
   L.LOCATION_ID, Max(MaxDate) 
FROM 
(
   (
    SELECT 
        LOCATION_ID, Max(LeadNote.NoteDate) AS MaxDate 
    FROM 
        LeadNote 
    JOIN 
        LOCATION 
    ON 
        LeadNote.LOCATION_ID = LOCATION.LOCATION_ID 
    GROUP BY 
        LOCATION_ID
   )
UNION 
   (
    SELECT 
       LOCATION_ID, Max(WORKORDER.WORKORDER_DATECREATED) AS MaxDate 
    FROM 
       WORKORDER 
    JOIN 
       LOCATION ON LOCATION_ID = WORKORDER_LOCATION_ID 
    GROUP BY 
       LOCATION_ID
   )
)

可能需要稍微调整......但是如果有效的话,可以通过@DrCopyPaste对评论表示赞赏:)

答案 3 :(得分:0)

您可以使用简单的连接和案例陈述来执行此操作:

SELECT 
   L.LOCATION_ID, 
   CASE WHEN(Max(LeadNote.NoteDate) IS NULL OR Max(LeadNote.NoteDate) > Max(WORKORDER.WORKORDER_DATECREATED) 
     THEN Max(LeadNote.NoteDate) 
     ELSE Max(WORKORDER.WORKORDER_DATECREATED) end AS maxDate
FROM 
   LOCATION AS L
LEFT JOIN LeadNote ON LeadNote.LOCATION_ID = LOCATION.LOCATION_ID 
LEFT JOIN WORKORDER ON L.LOCATION_ID = WORKORDER_LOCATION_ID 
GROUP BY L.LOCATION_ID