1

我的 SQL 技能非常基础,但我正在尝试为小型企业设置一个非营利性数据库。我有一个包含财务数据的表(extract_financial):

regno (organisation registration number, unique),
fystart (date, financial year start),
fyend (date, financial year end),
income,
exped (expenditure).

每个组织都会有一些不同财政年度的记录。并非所有记录都包括收入和支出值。

我只想显示每个组织的一条记录(包括 regno、fyend、income),即有任何收入的最新记录。

我尝试了以下脚本,改编自类似的问题,但它不起作用:

SELECT ef.regno, ef.fyend, ef.income  
FROM extract_financial ef  
    INNER JOIN  
    (  
        SELECT regno, Max(fyend) AS MaxOfFyend  
        FROM extract_financial  
        GROUP BY regno  
    ) AS efx  
        ON ef.regno = efx.regno   
            AND ef.fyend = efx.MaxOfFyend  
WHERE ef.income IS NOT NULL  

查找每个 [regno] 的最新条目的查询有效,但问题是最新记录中从来没有任何收入......所以我想我需要一个 IF THEN?

非常感谢您的帮助,谢谢!

4

1 回答 1

0

你很亲密。该WHERE子句需要进入子查询:

SELECT ef.regno, ef.fyend, ef.income  
FROM extract_financial as ef INNER JOIN  
     (SELECT regno, Max(fyend) AS MaxOfFyend  
      FROM extract_financial as ef
      WHERE ef.income IS NOT NULL
      GROUP BY regno  
     ) AS efx  
     ON ef.regno = efx.regno AND ef.fyend = efx.MaxOfFyend;
于 2016-12-06T20:49:09.020 回答