如何在相同条件下获取表格2的值

时间:2019-05-15 09:48:01

标签: php mysql

我有2个表,t_silm和t_revenue,并且我想对两个具有相同条件的表进行求和。这是我的表格示例:

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

我想得到结果:

avg = total / jumlah;

condition =  tw =4 and th = 2018;

请有人帮我吗?

$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++;  
  }

3 个答案:

答案 0 :(得分:0)

尝试此查询

SELECT t1.total as total1, t2.total as total2, total1/total2 as total_avg 
from t_slim t1 INNER JOIN t_revenue t2 on t1.th=t2.th 
and t2.tw=t1.tw WHERE t1.th=2018 and t1.tw=4

答案 1 :(得分:0)

不确定自己想要什么。

首先,您要对“总计”列求和:

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

然后您要对jumlah列求和:

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

将此2个查询归为1个查询:

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 

现在添加条件和平均值:

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 :(得分:0)

您可以使用此查询

SELECT sum(t_slim.total) as to1, sum(t_revenue.jumlah) as to2, to1/to2 as taverage 
from t_slim t1 INNER JOIN t_revenue t2 on t1.th=t2.th 
and t1.tw=t2.tw WHERE t1.th=2018 and t1.tw=4

这将为您提供平均值作为答案