【问题标题】:codeigniter: get percentage in multiple table by data categorycodeigniter:按数据类别获取多个表中的百分比
【发布时间】:2019-01-25 06:09:40
【问题描述】:

我有这样的桌子,

table_a

PID  Name   Type
1    a      selling
2    b      sampling
3    c      selling
4    d      sampling
5    e      selling

还有,

table_b

ID      PID   Qty
1       2     3
2       2     2
3       1     1
4       3     1
5       1     3
6       5     3
7       4     3
8       3     2

我需要这样展示,

output_selling

Name           Total_qty     Percentage
a              4             40%
c              3             30%
e              3             30%

还有,

output_sampling

Name           Total_qty     Percentage
b              5             62,5%
d              3             37,5%

我将如何在 CodeIgniter 中解决这个问题?

【问题讨论】:

  • function output_selling(){ $total = $this->db->select('SUM(table_b.Qty) as Total_qty', FALSE); $this->db->select('((sum(table_b.Qty)/'.$total.',0)*100 )as percentage', FALSE); $this->db->from('table_b'); $this->db->join('table_a', 'table_a.PID= table_b.PID', 'left'); $this->db->where('table_a.Type', "selling"); $this->db->group_by('table_b.PID'); $query = $this->db->get(); return $query->result(); }

标签: php mysql codeigniter model


【解决方案1】:

您可以在您的函数中使用下面的内容,并根据需要更改“采样”和“销售”:

$this->db->query("
SELECT dd.NAME, 
       dd.total_qty, 
       ( dd.total_qty / dd.totals ) * 100 AS Percentage 
FROM   (SELECT a.NAME, 
               Sum(b.qty)                            AS Total_qty, 
               (SELECT Sum(b1.qty) AS total 
                FROM   table_b b1 
                       JOIN table_a a1 
                         ON a1.pid = b1.pid 
                            AND a1.type = 'selling') AS totals 
        FROM   table_a a 
               JOIN table_b b 
                 ON b.pid = a.pid 
                    AND a.type = 'selling' 
        GROUP  BY a.pid) dd ");

请看下面的查询输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多