SQL仅显示趋势增加的条目

时间:2015-10-26 10:21:30

标签: mysql sql

我正在使用MySQL数据库,我需要编写一个SQL来显示purchase items所选时段的increasing trend over

以下SQL显示purchases上所有项目的selected period量。

SELECT
    ITEM_ID
    ITEM_NAME,
    SUM(IF(MONTH(TRANS_DATE)='6',NUM_PURCHASE,0)) AS PUR_JUNE,
    SUM(IF(MONTH(TRANS_DATE)='7',NUM_PURCHASE,0)) AS PUR_JULY,
    SUM(IF(MONTH(TRANS_DATE)='8',NUM_PURCHASE,0)) AS PUR_AUG,
    SUM(IF(MONTH(TRANS_DATE)='9',NUM_PURCHASE,0)) AS PUR_SEP
FROM
    TRANS_DETS
WHERE
    TRANS_DATE BETWEEN '2015-06-01' AND '2015-10-01'
GROUP BY
    ITEM_ID,
    ITEM_NAME

我可以请求帮助来写出我的要求吗?

1 个答案:

答案 0 :(得分:0)

您可以使用having子句执行此操作。假设你的意思是从一个月到下一个月有所增加:

SELECT ITEM_ID, ITEM_NAME,
       SUM(IF(MONTH(TRANS_DATE) = '6', NUM_PURCHASE, 0)) AS PUR_JUNE,
       SUM(IF(MONTH(TRANS_DATE) = '7', NUM_PURCHASE, 0)) AS PUR_JULY,
       SUM(IF(MONTH(TRANS_DATE) = '8', NUM_PURCHASE, 0)) AS PUR_AUG,
       SUM(IF(MONTH(TRANS_DATE) = '9', NUM_PURCHASE, 0)) AS PUR_SEP
FROM TRANS_DETS
WHERE TRANS_DATE BETWEEN '2015-06-01' AND '2015-10-01'
GROUP BY ITEM_ID, ITEM_NAME
HAVING ((PUR_JUNE < PUR_JULY) AND (PUR_JULY < PUR_AUG) AND
        (PUR_AUG < PUR_SEP));