如何在SQL中对结果进行分组?

时间:2015-09-28 07:37:42

标签: mysql sql select

我正在从1个表中进行查询,并使用UNION和2个select具有不同条件的查询。

SELECT *
FROM (
      SELECT DATE(MAX(RECEIVED)) DT,
             INFO CASH_INFO,
             SUM(IF(TRANS_TYPE = 714, AMOUNT, 0)) TOTAL_CASH,
             '' AS OTHER_INFO,
             0 AS TOTAL_CHEQUE,
             0 AS TOTAL_CREDIT
      FROM PAYMENT
      WHERE LOGIN = 'opensys' 
        AND SOURCE_OF_TRX = '245T2' 
        AND RET_CODE_ID IN (0, 106, 110) 
        AND RECEIVED >= DATE_SUB('2015-09-23 16:30:42', INTERVAL 7 DAY) 
        AND TRANS_TYPE = 714
      GROUP BY INFO
      UNION
      SELECT DATE(MAX(RECEIVED)) DT,
             '' AS CASH_INFO,
             0 AS TOTAL_CASH,    
             INFO OTHER_INFO,
             SUM(IF(TRANS_TYPE = 715, AMOUNT, 0)), -- TOTAL_CHEQUE,
             SUM(IF(TRANS_TYPE = 716, AMOUNT, 0)) -- TOTAL_CREDIT
      FROM PAYMENT
      WHERE LOGIN = 'opensys' 
        AND SOURCE_OF_TRX = '245T2' 
        AND RET_CODE_ID IN (0, 106, 110) 
        AND RECEIVED >= DATE_SUB('2015-09-23 16:30:42', INTERVAL 7 DAY) 
        AND TRANS_TYPE in (715, 716)
      GROUP BY INFO
     ) A
GROUP BY CASH_INFO, OTHER_INFO
ORDER BY DT

结果并不准确,因为记录没有对同一日期记录进行分组。

我想要实现的是将结果分组到相同的日期。

P / S:最后2条记录将始终返回相同的日期。这意味着2015年9月23日将有2个日期。

很抱歉,我无法发布图片,所以我必须将其链接到我的谷歌硬盘。 image

1 个答案:

答案 0 :(得分:0)

不幸的是,MySQL允许您发布的查询但在几乎所有RDMS SQL引擎中都会失败,因为您选择的项目*不限于聚合查询中的GROUP BY子句。如果您设置了sql_mode to ANSI,则此查询会出现GROUP BY错误。

考虑聚合查询的更正ANSI语法,仅选择要聚合的字段,然后按日期,cash_info和other_info字段进行分组。

SELECT DT, 
       CASH_INFO, 
       Sum(TOTAL_CASH), 
       OTHER_INFO, 
       Sum(TOTAL_CHEQUE), 
       Sum(TOTAL_CREDIT)
FROM (
      SELECT DATE(MAX(RECEIVED)) DT,
             INFO CASH_INFO,
             SUM(IF(TRANS_TYPE = 714, AMOUNT, 0)) TOTAL_CASH,
             '' AS OTHER_INFO,
             0 AS TOTAL_CHEQUE,
             0 AS TOTAL_CREDIT
      FROM PAYMENT
      WHERE LOGIN = 'opensys' 
        AND SOURCE_OF_TRX = '245T2' 
        AND RET_CODE_ID IN (0, 106, 110) 
        AND RECEIVED >= DATE_SUB('2015-09-23 16:30:42', INTERVAL 7 DAY) 
        AND TRANS_TYPE = 714
      GROUP BY INFO
      UNION
      SELECT DATE(MAX(RECEIVED)) DT,
             '' AS CASH_INFO,
             0 AS TOTAL_CASH,    
             INFO OTHER_INFO,
             SUM(IF(TRANS_TYPE = 715, AMOUNT, 0)), -- TOTAL_CHEQUE,
             SUM(IF(TRANS_TYPE = 716, AMOUNT, 0)) -- TOTAL_CREDIT
      FROM PAYMENT
      WHERE LOGIN = 'opensys' 
        AND SOURCE_OF_TRX = '245T2' 
        AND RET_CODE_ID IN (0, 106, 110) 
        AND RECEIVED >= DATE_SUB('2015-09-23 16:30:42', INTERVAL 7 DAY) 
        AND TRANS_TYPE in (715, 716)
      GROUP BY INFO
     ) A
GROUP BY DT, CASH_INFO, OTHER_INFO;