dongyanjing5975 2019-05-15 09:48
浏览 36
已采纳

如何获得具有相同条件的值表格2表格

I have 2 tables, t_silm and t_revenue, and I want to sum some both tables with the same condition. This is sample my table:

https://ibb.co/JtCp80w

t_silm

bl - th - tw - total
10 - 2018 - 4 - 100
11 - 2018 - 4 - 200
12 - 2018 - 4 - 300


t_revenue

bl - th - tw - jumlah
10 - 2018 - 4 - 25
11 - 2018 - 4 - 70
12 - 2018 - 4 - 45

I want to get the result:

avg = total / jumlah;

condition =  tw =4 and th = 2018;

Please can somebody help me?

$query = "SELECT sum(t_slim.pemakaian_309) as to1, sum(t_revenue.jumlah) as to2, to1/to2 as taverage 
            from t_slim t1 INNER JOIN t_revenue t2 on t1.tahun=t2.tahun 
            and t1.triwulan=t2.triwulan WHERE t1.tahun=$tahun and t1.triwulan=$triwulan GROUP BY bulan";
  
  $hasil = mysql_query($query);
  $baris = 3;
   while ($data = mysql_fetch_array($hasil))
  {
  $worksheet2->write_string(11, $baris, number_format($data['taverage'],2),$format2);
  $baris++;  
  }

</div>
  • 写回答

3条回答 默认 最新

  • duanbozhong9689 2019-05-15 10:06
    关注

    not sure about what you want.

    First you want to sum the column 'total' :

    SELECT SUM(total) as total1, th, tw FROM t_silm GROUP BY th,tw
    

    Then you want to sum the column jumlah :

    SELECT SUM(jumlah) as total2, th, tw FROM t_silm GROUP BY th,tw
    

    Group this 2 query in 1 query :

    SELECT * 
    FROM 
    (SELECT SUM(total) as total1, th, tw FROM t_silm GROUP BY th,tw ) as T1
    INNER JOIN 
     (SELECT SUM(jumlah) as total2, th, tw FROM t_silm GROUP BY th,tw) as T2
          on T2.tw =T1.tw AND T2.th=T1.th 
    

    Now add the condition and the avg :

    SELECT T1.th, T1.tw, total1/total2 as avg
    FROM
    (SELECT SUM(total) as total1, th, tw FROM t_silm GROUP BY th,tw ) as T1
        INNER JOIN 
         (SELECT SUM(jumlah) as total2, th, tw FROM t_silm GROUP BY th,tw) as T2
              on T2.tw =T1.tw AND T2.th=T1.th 
    WHERE T1.tw =4 and T1.th = 2018;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失