如何使用php查找两个不同的sql查询的平均值

时间:2018-03-07 13:11:14

标签: php sql

以下是我的代码:

  $sql = "SELECT count(EventCode) as Total_Event FROM sample where Age between 5 and 10";
  $stmt = sqlsrv_query( $conn, $sql )

  $sql1 = "SELECT count(EventCode) as Total_Event FROM sample where Age between 50 and 80";
  $stmt1 = sqlsrv_query( $conn, $sql1 );

从上面的查询中,我可以计算sqlsql1语句发生的事件数。

我需要对这两个查询值sqlsql1

取平均值

请帮助我如何更改我的代码以实现它。

2 个答案:

答案 0 :(得分:2)

您希望两个不同年龄段的人的平均事件数量。这真的很奇怪,但最简单的方法是单个查询:

SELECT count(EventCode) / 2 as strange_average_calculation
FROM sample 
WHERE Age between 5 and 10 OR Age between 50 and 80;

答案 1 :(得分:0)

你可以使用sql函数,即SELECT AVG(column_name)

  $sql = "SELECT AVG(EventCode) as avg_Event FROM sample where Age between 5 and 10";
  $stmt = sqlsrv_query( $conn, $sql )

  $sql1 = "SELECT AVG(EventCode) as avg_Event_2 FROM sample where Age between 50 and 80";
  $stmt = sqlsrv_query( $conn, $sql1 );