如何按月在mysql中对concat进行分组并显示?

时间:2018-07-10 06:07:36

标签: php mysql

我需要显示图表上有多少患者,在当年的数月内按月在我的图表上求医。目前,我的查询提供了总计有多少患者的计数,而不是每种药物,而且我不知道如何解决。

当前查询:

SELECT     `brands`.`name_et` AS `brand_name`, 
           `patients`.`created_at`, 
            count(*)                                                  AS count, 
            monthname(patients.created_at)                            AS month, 
            year(patients.created_at)                                 AS year 
FROM       `patients` 
INNER JOIN `brands` 
ON         `brands`.`id` = `patients`.`brand_id` 
INNER JOIN `brand_presentations` 
ON         `brand_presentations`.`brand_id` = `brands`.`id` 
INNER JOIN `dosage_forms` 
WHERE      `brand_presentations`.`manufacturer_id` = ? 
GROUP BY   `month`, 
           `year`, 
           `brand_name` 
ORDER BY   `year` ASC

这是我当前的json响应

[  
   {  
      "brand_name":"med 1",
      "created_at":"2018-05-15 07:20:03",
      "count":1,
      "month":"May",
      "year":2018
   },
   {  
      "brand_name":"med 2",
      "created_at":"2018-07-03 14:57:42",
      "count":1,
      "month":"July",
      "year":2018
   },
   {  
      "brand_name":"med 3",
      "created_at":"2018-07-03 14:57:42",
      "count":2,
      "month":"July",
      "year":2018
   },
   {  
      "brand_name":"med 4",
      "created_at":"2018-07-03 15:00:07",
      "count":3,
      "month":"July",
      "year":2018
   }
]

这是我期望的json响应。

[  
   {  
      "May":[  
         {  
            "brand_name":"Med 1",
            "count":1,
            "year":2018
         },
         {  
            "brand_name":"Med 3",
            "count":3,
            "year":2018
         },
         {  
            "brand_name":"Med 2",
            "count":4,
            "year":2018
         }
      ]
   }
]

所需结果的图片(通过硬编码创建)

enter image description here

用PHP生成所需的json更好还是可以在mySql中完成?

0 个答案:

没有答案