如何在Mysqli查询中将行转换为列

时间:2019-02-19 10:38:44

标签: mysql

我想将Month数据转换为列

此查询获得以下结果

enter image description here

SELECT CONCAT(MONTHNAME(C.`ClientServiceDate`),'-',YEAR(C.`ClientServiceDate`)) AS 'Month',ME.`MethodName`,
       COUNT(C.`ContraceptiveMethod`) AS 'TotalUser',
       MONTH(C.ClientServiceDate) AS 'Month'
FROM mwra AS M
JOIN client_information AS C ON (C.MwraId = M.MwraId)
LEFT JOIN methods AS ME ON (ME.MethodId = C.ContraceptiveMethod)
WHERE C.FpUserStatus = 'New'
GROUP BY ME.MethodId,MONTH(C.ClientServiceDate)

1 个答案:

答案 0 :(得分:0)

我前段时间做了类似的事情。

您可以尝试使用准备好的语句。获取月份名称

SET @headers = (
SELECT
    GROUP_CONCAT( DISTINCT
        CONCAT(
            'SUM( IF(MONTH(C.`ClientServiceDate`) = ', 
             MONTH(C.`ClientServiceDate`), 
            'C.ContraceptiveMethod,0) ) AS '
            , MONTHNAME(C.`ClientServiceDate`)
            )
            ORDER BY C.`ClientServiceDate`
    )
FROM client_information  as C
);

然后将这些标头用于准备好的语句:

SET @sql = CONCAT('SELECT ', @headers, 'REMAINING QUERY');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;