What is the equivalent of aggregate functions FIRST and LAST from MySQL in Firebird

时间:2016-02-03 04:23:49

标签: sql firebird

Does anyone know what is the equivalent of the aggregate functions FIRST and LAST from MySQL to Firebird. I have this inventory master table that looks like this:

DATE       |ITEM_CODE       | BEG | + | - | - | - | + | + | + | + | - | - | END
2015-10-27 | 000000000MS016 |12.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12.5
2015-10-27 | 000000000PN044 |   0 |10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |   10 
2015-10-27 | 000000000VI064 | 440 | 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |  445 
2015-10-27 | 000000000VI029 | 274 | 0 | 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |  269

2015-10-28 | 000000000MS016 |12.5 |20 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 32.5
2015-10-28 | 000000000PN044 |  10 |50 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |   60 
2015-10-28 | 000000000VI064 | 445 | 0 | 0 |10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |  435 
2015-10-28 | 000000000VI029 | 269 | 0 | 0 | 0 |20 | 0 | 0 | 0 | 0 | 0 | 0 |  249

2015-10-29 | 000000000MS016 |32.5 | 0 |10 | 0 | 0 | 0 | 0 | 0 |30 | 0 | 5 | 47.5
2015-10-29 | 000000000PN044 |  60 | 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |   65 
2015-10-29 | 000000000VI064 | 435 | 0 | 0 | 0 | 0 |10 | 0 | 0 | 0 | 8 | 0 |  437 
2015-10-29 | 000000000VI029 | 249 |35 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 |  280

2015-10-30 | 000000000MS016 |47.5 | 0 |15 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 32.5
2015-10-30 | 000000000PN044 |  65 | 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 0 |   65 
2015-10-30 | 000000000VI064 | 437 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |  437 
2015-10-30 | 000000000VI029 | 280 | 0 | 5 | 0 | 5 | 0 | 0 | 6 | 0 | 3 | 0 |  273

and I have this SELECT clause:

SELECT
  INV.ITEM_CODE,
  FIRST(INV.BEG_QTY) AS BEG_QTY,
  SUM(INV.REC_QTY) AS REC_QTY,
  SUM(INV.RET_QTY) AS RET_QTY,
  SUM(INV.SOLD_QTY) AS SOLD_QTY,
  SUM(INV.BO_QTY) AS BO_QTY,
  SUM(INV.ADJ_QTY) AS ADJ_QTY,
  SUM(INV.COUNT_P) AS COUNT_P,
  SUM(INV.COUNT_C) AS COUNT_C,
  SUM(INV.TRANS_IN) AS TRANS_IN,
  SUM(INV.TRANS_OUT) AS TRANS_OUT,
  SUM(INV.DELIVERY) AS DELIVERY,
  LAST(INV.END_QTY) AS END_QTY
FROM INV_MASTER INV
WHERE (INV.INV_DATE BETWEEN '2015-10-27' AND '2015-10-31')
GROUP BY INV.ITEM_CODE
ORDER BY INV.ITEM_CODE

and the result SHOULD look like this:

ITEM_CODE      | BEG | + | - | - | - | + | + | + | + | - | - | END    
000000000MS016 |12.5 |20 |25 | 0 | 0 | 0 | 0 | 0 |30 | 0 | 5 | 32.5
000000000PN044 |   0 |70 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 0 |   65 
000000000VI064 | 440 | 5 | 0 |10 | 0 |10 | 0 | 0 | 0 | 8 | 0 |  437 
000000000VI029 | 274 |35 |10 | 0 |25 | 0 | 0 | 6 | 0 | 3 | 4 |  273

but I'm having a problem with the FIRST and LAST aggregate functions, I'm using firebird v2.5. How can i do this?

1 个答案:

答案 0 :(得分:0)

您应该能够将LAST替换为

(SELECT END_QTY FROM INV_MASTER 
   WHERE ITEM_CODE = INV.ITEM_CODE 
   AND INV_DATE = MAX(INV.INV_DATE)) AS END_QTY

这将选择当前项目的END_QTY,其中包含该项目的最高日期。