如何将列命名为星期几

时间:2016-12-17 23:50:34

标签: mysql sql mariadb

我有这个约会,但我不得不把这一天当作。

   select `a`.`aplicativo` AS `PROGRAMA`,
          sum((cast(`r`.`created_at` as date) = curdate())) AS `HOJE`,
          sum((cast(`r`.`created_at` as date) = (curdate() - 1))) AS `ONTEM`,
          sum((cast(`r`.`created_at` as date) = (curdate() - 2))) AS `2_DIAS`
   from (`registration` `r` 
         join `aplicativos` `a` on ((`r`.`app_id` = `a`.`id`))) 
   group by `r`.`app_id` 

我已尝试使用以下命令给出错误。

sum((cast(`r`.`created_at` as date) = (curdate() - 1))) AS DATE_FORMAT(curdate(),'%a %e') 

我希望在每一列的总和中出现

Sunday | Monday | Tuesday | Wednesday
65       54       99        100

它无法修复,因为每一天都会改变。 今天是星期天,将出现星期六,星期五...... 但明天是星期一那么它应该出现:星期天,星期六....

明天将是下面的另一个结果

Monday | Tuesday | Wednesday | Thursday
54       99        100         85

1 个答案:

答案 0 :(得分:1)

SELECT a.aplicativo AS programa,
  SUM(CASE WHEN dayofweek(r.created_at)=1 THEN 1 ELSE 0 END) AS sunday,
  SUM(CASE WHEN dayofweek(r.created_at)=2 THEN 1 ELSE 0 END) AS monday,
  /* ... */
  SUM(CASE WHEN dayofweek(r.created_at)=7 THEN 1 ELSE 0 END) AS saturday
FROM registration r
  JOIN aplicativos a ON a.id=r.app_id
WHERE r.created_at>=(curdate()-6)
GROUP BY a.aplicativo