php - php 中的 codeigniter 交叉表

标签 php mysql codeigniter

我使用以下代码

  Sample Gender Handedness
    1   Female  Right-handed
    2   Male    Left-handed
    3   Female  Right-handed
    4   Male    Right-handed
    5   Male    Left-handed
    6   Male    Right-handed
    7   Female  Right-handed
    8   Female  Left-handed
    9   Male    Right-handed
    10  Female  Right-handed

              Left-
             handed    Right-
                       handed Total
    Males   2   3   5
    Females 1   4   5
    Total   3   7   10

我有上面的表,我需要得到第二个表。我需要使用交叉表,但我不知道该怎么做。有人能帮助我吗。我在 codeigniter 中执行此操作。

最佳答案

您可以通过查询来完成

SELECT gender,
       SUM(CASE WHEN Handedness = 'Left-handed' THEN 1 ELSE 0 END) left_handed,
       SUM(CASE WHEN Handedness = 'Right-handed' THEN 1 ELSE 0 END) right_handed,
       COUNT(*) total
  FROM Table1
 GROUP BY gender WITH ROLLUP

输出:

| GENDER | LEFT_HANDED | RIGHT_HANDED | TOTAL |
|--------|-------------|--------------|-------|
| Female |           1 |            4 |     5 |
|   Male |           2 |            3 |     5 |
| (null) |           3 |            7 |    10 | -- this is your total produced by WITH ROLLUP

Here is SQLFiddle demo


I'm not an expert in CI but your code might look like

$sql = "SELECT gender,
               SUM(CASE WHEN Handedness = 'Left-handed' THEN 1 ELSE 0 END) left_handed,
               SUM(CASE WHEN Handedness = 'Right-handed' THEN 1 ELSE 0 END) right_handed,
               COUNT(*) total
          FROM Table1
         GROUP BY gender WITH ROLLUP";
$data = $this->db->query($sql)->result_array();

关于php - php 中的 codeigniter 交叉表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18778602/

相关文章:

php - 使用外键获取值时出现问题

php - 使用 php mysql 将数据插入数据库时​​比较两个表

php - $result 的 Codeigniter num_rows() 始终返回 0

php - { } codeigniter 模型/ View 中的大括号

php - 如何从旋转/缩放中获取 SVG 变换矩阵值

php - mysql搜索2个有重叠的表

mysql - 在mysql中导入数据而不覆盖某些列

php - 在 mysqli_fetch_object 中使用 foreach 而不是 while

mysql - 如何设计数据库来维护和显示支持不同语言(i18n)的主数据?

php - 可以增加变量的声明吗?