使用mysql和php计算多个列

时间:2012-05-28 11:36:22

标签: php mysql codeigniter-2

我有一个包含以下列的销售表

  • 名称
  • 类型(学生,成人,工人)
  • 销售(A,B,C,D)
  • 成本
  • location(1,2,3,4)

我希望通过名称获取与名称和组相关的类型,销售和位置的计数,以便我可以在表格上显示 enter image description here

是否可以使用查询>

获取所有分组值

任何帮助都会受到赞赏..

2 个答案:

答案 0 :(得分:1)

使用GROUP BY然后SUM(condition)获取您的点数:

SELECT   name AS Name,
         SUM(type     = 'worker' ) AS Worker,
         SUM(type     = 'student') AS Student,
         SUM(type     = 'adult'  ) AS Adult,
         SUM(sales    = 'A'      ) AS A,
         SUM(sales    = 'B'      ) AS B,
         SUM(sales    = 'C'      ) AS C,
         SUM(sales    = 'D'      ) AS D,
         SUM(location = 1        ) AS Location1,
         SUM(location = 2        ) AS Location2,
         SUM(location = 3        ) AS Location3,
         SUM(location = 4        ) AS Location4
FROM     sales
GROUP BY Name

答案 1 :(得分:0)

function getDistributorStat() // One Distributor
{

    $this ->db->select("count(*) ch1 ,
                        sum(c_privi_flag = 'Y') ch2, sum(c_happy1_flag = 'Y') ch3, sum(c_happy2_flag = 'Y') ch4,
                        sum(date(D_JOIN) = CURRENT_DATE) nch1,
                        sum(date(d_privi_activated) = CURRENT_DATE) nch2,
                        sum(date(d_happy1_activated) = CURRENT_DATE) nch3,
                        sum(date(d_happy2_activated) = CURRENT_DATE) nch4"
                        );
    $this->db->from('bc_master');
    $query = $this ->db->get()->row();
    $data['distributors']=$query->ch1;
    $data['privilaged']=$query->ch2;
    $data['happy1']=$query->ch3;
    $data['happy2']=$query->ch4;
    $data['new_distributors']=$query->nch1;
    $data['new_privilaged']=$query->nch1;
    $data['new_happy1']=$query->nch1;
    $data['new_happy2']=$query->nch1;

    return $data;

}