2

我有这样的查询

SELECT        
  A.JBCo, A.Invoice, MAX(B.JCDate) AS LastWorkedDay, C.Description
FROM            
  C 
INNER JOIN A ON 
  C.JBCo = A.JBCo AND 
  C.BillMonth = A.BillMonth AND 
  C.BillNumber =  A.BillNumber 
INNER JOIN B ON 
  C.JBCo = B.JBCo AND 
  C.BillMonth = B.BillMonth AND 
  C.BillNumber = B.BillNumber AND 
  C.Line = B.Line
GROUP BY 
  A.Invoice, A.JBCo, C.Description
HAVING        
  (A.JBCo = 12) AND 
  (A.Invoice LIKE '%1000223%')

得到类似的结果

Co          invoice             Lastworkdate        description
12         1000223              2012-12-9             Labor
12         1000223              2012-12-7             Equipment
12         1000223              2012-12-2              Material

我需要一个查询来产生类似“劳动力”的结果,然后在劳动力中使用 lastWorkedDate,如果发票中没有劳动力,则使用最后日期。所以最终结果将只有每张发票的一行,在这种情况下将是(无需显示描述)。我尝试使用 case when 语句,但我无法正确使用它。请帮忙。谢谢

12     1000223      2012-12-09     
4

2 回答 2

1

如果向查询中添加 case 语句,则只能获取 LaborDates 的 MaxDate。case 表达式如下所示:

MAX(case when C.Description = 'Labor' then B.JCDate else null end) AS LastLaborDay

如果您添加并运行它,您现在将有两列。一个有最大日期,另一个有最大劳动日期……如果是非劳动,则为 null。

您现在可以将此查询结果用作嵌套表。您按发票分组以减少到单行。您还可以找到两个日期列的最大值。如果没有劳动力,该最大值将为空。因此,使用 COALESCE() 选择第一个非空值。

它看起来像这样:

select JBCO, invoice, max(LastLaborDay), max(LastWorkedDay), coalesce(max(LastLaborDay), max(LastWorkedDay))
from 
(
SELECT        
  A.JBCo, A.Invoice, MAX(B.JCDate) AS LastWorkedDay, 
  MAX(case when C.Description = 'Labor' then B.JCDate else null end) AS LastLaborDay, 
  C.Description
FROM            
  C 
INNER JOIN A ON 
  C.JBCo = A.JBCo AND 
  C.BillMonth = A.BillMonth AND 
  C.BillNumber =  A.BillNumber 
INNER JOIN B ON 
  C.JBCo = B.JBCo AND 
  C.BillMonth = B.BillMonth AND 
  C.BillNumber = B.BillNumber AND 
  C.Line = B.Line
GROUP BY 
  A.Invoice, A.JBCo, C.Description
HAVING        
  (A.JBCo = 12) AND 
  (A.Invoice LIKE '%1000223%')
) TBL1

看看这个 SQL Fiddle,如果需要,可以调整它。

于 2013-11-12T21:16:35.150 回答
0

尝试这个

SELECT        
  A.JBCo, A.Invoice, 
CASE WHEN description="Labor" THEN MAX(B.JCDate) ELSE MAX(B.JCDate) END AS LastWorkedDay, 
  C.Description
FROM            
  C 
INNER JOIN A ON 
  C.JBCo = A.JBCo AND 
  C.BillMonth = A.BillMonth AND 
  C.BillNumber =  A.BillNumber 
INNER JOIN B ON 
  C.JBCo = B.JBCo AND 
  C.BillMonth = B.BillMonth AND 
  C.BillNumber = B.BillNumber AND 
  C.Line = B.Line
GROUP BY 
  A.Invoice
HAVING        
  (A.JBCo = 12) AND 
  (A.Invoice LIKE '%1000223%')
于 2013-11-12T20:47:46.727 回答