MySQL到PHP数组分组重复值

时间:2011-05-19 17:14:46

标签: php mysql sql multidimensional-array foreach

请对我温柔,因为我正在学习,因为我使用手册,试验和错误以及(ahem)开源软件的逆向工程。

我有一个MySQL查询返回如下表格(查询已经相当复杂,因为它包括来自连接表的总和和计数):

   DATE      ANSWER   CATEGORY    COUNT
2011-01-01      Y       CAT1       22
2011-01-01      Y       CAT2       220
2011-01-01      N       CAT1       14
2011-01-01      N       CAT2       530
2011-01-02      Y       CAT1       50
2011-01-02      Y       CAT2       270
2011-01-02      N       CAT1       18
2011-01-02      N       CAT2       576

我需要将所有内容都放在带有日期的单行上,例如

   DATE      Total Y     Total N     Total Cat1    Total Cat2    Total Overall
2011-01-01     242         544           36            750            786
2011-01-02     320         594           68            750            846

现在我假设要达到这些数字,我需要将它们分组成一个多维数组,以便我可以像这样使用数字:

Array
(
 2011-01-01 => Array (
    Y => Array(
        [CAT1] = 22
        [CAT2] = 220
        )
    N => Array(
        [CAT1] = 14
        [CAT2] = 530
        )
     )
 2011-01-02 => Array (
    Y => Array(
        [CAT1] = 50
        [CAT2] = 270
        )
    N => Array(
        [CAT1] = 18
        [CAT2] = 576
        )
     )
)

但这就是我陷入困境的地方我似乎无法弄清楚foreach循环在这个实例中将数据导入数组,一旦它在那里,我该如何在表中显示它?

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

您可以从查询本身获得结果。

我知道这不是最好的查询,但它是为了让您了解如何解决您想要的问题

SELECT theDate AS `DATE`, 
    (SELECT SUM(theCount) FROM st WHERE theAnswer = 'Y' AND theDate = a.theDate) AS 'Total Y',
    (SELECT SUM(theCount) FROM st WHERE theAnswer = 'N' AND theDate = a.theDate) AS 'Total N',
    (SELECT SUM(theCount) FROM st WHERE theCategory = 'CAT1' AND theDate = a.theDate) AS 'Total Cat1',
    (SELECT SUM(theCount) FROM st WHERE theCategory = 'CAT2' AND theDate = a.theDate) AS 'Total Cat2',
    (SELECT SUM(theCount) FROM st WHERE theCategory IN('CAT1','CAT2') AND theDate = a.theDate) AS 'Total Overall'
FROM st AS a
GROUP BY theDate

结果:

   DATE      Total Y     Total N     Total Cat1    Total Cat2    Total Overall
2011-01-01     242         544           36            750            786
2011-01-02     320         594           68            846            914

答案 1 :(得分:1)

SELECT
  DATE,
  SUM(CASE ANSWER WHEN 'Y' THEN COUNT ELSE 0 END) AS TotalY,
  SUM(CASE ANSWER WHEN 'N' THEN COUNT ELSE 0 END) AS TotalN,
  SUM(CASE CATEGORY WHEN 'CAT1' THEN COUNT ELSE 0 END) AS TotalCat1,
  SUM(CASE CATEGORY WHEN 'CAT2' THEN COUNT ELSE 0 END) AS TotalCat2,
  SUM(COUNT) AS TotalOverall
FROM subquery
GROUP BY DATE

答案 2 :(得分:0)

您可以直接从SQL数据库中提取所需的数据。

尝试:

SELECT `DATE`, ANSWER, SUM(`COUNT`) as TOTAL 
FROM table -- Change this!
GROUP BY `DATE`, ANSWER

用CATEGORY替换ANSWER以获得总类别。