sql Aggregate函数的多个条件

时间:2017-01-17 19:27:33

标签: mysql

如何在sql Aggregate函数上按多个条件进行分组。例如,我有两个表SalesAccounts

Sales

ID  |  identifier_one  |  identifier_two  | quantity | date
1   |       1          |       A1         |    1     |  2017-01-01
2   |       1          |       B1         |    1     |  2017-01-01
3   |       1          |       A1         |    1     |  2017-01-02

查询应该如此填写帐户表

Accounts

ID  |  identifier_one  |  identifier_two  |  current_month  |  current_year
1   |       1          |       A1         |    2            |     2
2   |       1          |       B1         |    1            |     1 

我有此查询,但只考虑帐户identifier_one,因此在此示例中,帐户中的两个条目都有33

$sales = DB::select('SELECT
                            identifier_one,
                            SUM(IF(YEAR(`date`) = YEAR(CURDATE()), quantity, 0)) AS current_year,
                            SUM(IF(YEAR(`date`) = YEAR(CURDATE()) AND MONTH(`date`) = MONTH(CURDATE() ), quantity, 0)) AS current_month,
                            SUM(IF(YEAR(`date`) = YEAR(CURDATE()) - 1, quantity, 0)) AS last_year,
                            SUM(IF(YEAR(`date`) = YEAR(CURDATE()) AND MONTH(`date`) = MONTH(CURDATE()) - 1, quantity, 0)) AS last_month
                        FROM sales
                        GROUP BY identifier_one'); 

foreach ($sales as $sale) {

                    DB::table('accounts')
                        ->where([
                            ['identifier_one', '=', $sale->identifier_one]
                        ])
                        ->update([
                            'current_year'  => $sale->current_year,
                            'current_month' => $sale->current_month,
                            'last_month'    => $sale->last_month,
                            'last_year'     => $sale->last_year
                        ]);


                }

1 个答案:

答案 0 :(得分:0)

好像你只需要添加一个,并将字段名称添加到组中。 您可能还希望将select_two添加到select中,以防需要更新where子句以考虑这两个标识符。 (可能)

SELECT identifier_one
     , identifier_two  --not required but may be useful as you seem to filter on identifier_one later; maybe you also need the 2nd one...
     , SUM(IF(YEAR(`date`) = YEAR(CURDATE()), quantity, 0)) AS current_year,
     , SUM(IF(YEAR(`date`) = YEAR(CURDATE()) AND MONTH(`date`) = MONTH(CURDATE() ), quantity, 0)) AS current_month
     , SUM(IF(YEAR(`date`) = YEAR(CURDATE()) - 1, quantity, 0)) AS last_year
     , SUM(IF(YEAR(`date`) = YEAR(CURDATE()) AND MONTH(`date`) = MONTH(CURDATE()) - 1, quantity, 0)) AS last_month
FROM sales
GROUP BY identifier_one, identifier_two --this is what you're missing