简体   繁体   中英

Change Mysql Group by value

Is it possible to change GROUP BY parameter in MySQL query? For example if user chooses period by 'week' in drop down list, to group results by week, if 'month' then by month, same with 'year'. I am working with Symfony2 and getting $period variable from request

 $period = $request->get('period');

 // value of $period are: 'day','week', 'month', 'year' 

 $sql_query = "SELECT COUNT(*), DATE_FORMAT(like_date, \"%y-%m-%d\" ) AS day, 
 WEEK(like_date) as week, MONTH(like_date) as month, YEAR(like_date) as year
 FROM user_likes
 GROUP BY date";

In this query I'm grouping only by date. Is it possible to change GROUP BY parameter using CASE inside query?

RE, your comment value of $period are: 'day', 'week', 'month', 'year'

This may be the simplest solution

$sql_query = "SELECT COUNT(*), 
                     DATE_FORMAT(like_date, \"%y-%m-%d\" ) AS date, 
                     DAY(like_date) as day, 
                     WEEK(like_date) as week, 
                     MONTH(like_date) as month, 
                     YEAR(like_date) as year
              FROM user_likes
              GROUP BY $period";

Assuming $period variable contains one of these values {'day','week','month','year'}

SET @period := 'month';
SELECT 
                     COUNT(*), 
                     DATE_FORMAT(like_date, "%Y-%m-%d" ) AS date, 
                     DAY(like_date) as day, 
                     WEEK(like_date) as week, 
                     MONTH(like_date) as month, 
                     YEAR(like_date) as year
FROM user_likes
GROUP BY
     CASE 
        WHEN @period = 'day' THEN DATE_FORMAT(like_date,"%Y-%m-%d")
        WHEN @period = 'week' THEN WEEK(like_date) 
        WHEN @period = 'month' THEN MONTH(like_date) 
        WHEN @period = 'year' THEN YEAR(like_date)
      END

SQL FIDDLE

N:B: Although @RiggsFolly already gave an answer. I felt an urge to give this answer right after seeing your comment:

@MarcB but in CASE I need to compare columns in order to switch. $period is not column.

You can build dynamic query according to @Marc B. Please check the SQL demo for better understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM