每个给定年份的SQL maxdate

时间:2014-07-25 17:14:57

标签: sql sql-server-2008

通过帖子搜索发现了类似的问题,但无法翻译答案以解决我遇到的问题。此选择的输出应为account_id,每个日历年中最近的wip_stmt_date具有受到攻击的财务,其中一些我从下面的数据输出中排除。任何建议将不胜感激。


SELECT a.account_id,
   a.wip_stmt_date,
   SUM(b."Cost to Complete") AS "Cost to Complete",
   SUM(b."Estimated Gross Profit") AS "Estimated Gross Profit",
   SUM(b."Earned Gross Profit") AS "Earned Gross Profit"

FROM WIP a
   inner join (
SELECT wip_id,
    SUM(wip_compl_cost) AS "Cost to Complete",
    SUM(est_gross_profit) AS "Estimated Gross Profit",
    SUM(earned_gross_profit) AS "Earned Gross Profit"
        FROM WIP_Detail GROUP BY wip_id
         ) b

 ON a.wip_id = b.wip_id

 WHERE year(a.wip_stmt_date) > 2008 and account_id is not null

 GROUP BY a.account_id, a.wip_stmt_date

 account_id      wip_stmt_date        Cost to Complete
    400      1996-06-30 00:00:00.000     989704310 don't need
    400      1996-09-30 00:00:00.000    1168271446 don't need
    400      1996-12-31 00:00:00.000    1200403025
    400      1997-03-31 00:00:00.000    1232629057 don't need
    400      1997-06-30 00:00:00.000    1114344673 don't need
    400      1997-09-30 00:00:00.000    1304671991 don't need
    400      1997-12-31 00:00:00.000    1407410337
    400      1998-03-31 00:00:00.000    1549329678 don't need
    400      1998-09-30 00:00:00.000    1608083965
    400      1999-03-31 00:00:00.000    1663183272
    400      2000-03-31 00:00:00.000    1673019904
    400      2001-03-31 00:00:00.000    1828818751
    400      2002-09-30 00:00:00.000    2847506038 don't need
    400      2002-12-31 00:00:00.000    3366648755

1 个答案:

答案 0 :(得分:0)

这是SQL Server的答案。其他DBMS可能需要更改语法。

SELECT account_id, 
MAX(wip_stmt_date), 
SUM("Cost to Complete") AS "Cost to Complete", 
SUM("Estimate Gross Profit") AS "Estimated Gross Profit", 
SUM("Earned Gross Profit) AS "Earned Gross Profit"
FROM wip_id a (NOLOCK)
INNER JOIN WIP b
ON a.wip_id = b.WIP
WHERE account_id IS NOT NULL
GROUP BY DATEPART(YEAR, wip_stmt_date), account_id