SUM添加不同的表相同的ID

时间:2015-12-30 18:54:10

标签: sql oracle

我不知道如何解决这个问题。

if($_POST['submit'])
{
    $keywords = $_POST['keyword'];


        $returned_results = array ();
        $where = "";

        $keywords = preg_split('/[\s]+/', $keywords);
        $total_keywords = count($keywords);

        foreach ($keywords as $key=>$keyword)
        {
            $where .= "keywords LIKE '%$keyword%'";
            if ($key != ($total_keywords - 1))
                $where .= " OR ";
        }


    $query = "SELECT title, url FROM pages WHERE $where";

    $q_result = mysql_query($query) or die (mysql_error());
                    if (mysql_num_rows ($q_result) <= 0)
                    {
                        echo "";
                    }
                    else
            {
                        while ($row = mysql_fetch_assoc($q_result))
                        {
                        $url = $row['url'];
                        $title = $row['title'];
                        echo "<br><a style='text-align: center;' href=\"../$url\">$title</a><hr width='35%'>";;
                        }
            }

}

此查询返回2列,如:

SELECT c.NIF,
  v.preu
FROM CLIENTS c
INNER JOIN RESERVES_VIATGES r
INNER JOIN VIATGES v
ON r.CODI_VIATGE = v.CODI
ON c.NIF         = r.NIF_CLIENT
GROUP BY c.NIF, v.preu;

我想选择具有相同NIF的价格的和。 我该怎么做?感谢

2 个答案:

答案 0 :(得分:1)

您可以使用SUM()聚合函数,例如

SELECT c.NIF, sum(v.preu) as Sum_price
FROM CLIENTS c
INNER JOIN RESERVES_VIATGES r
ON c.NIF = r.NIF_CLIENT
INNER JOIN VIATGES v
ON r.CODI_VIATGE = v.CODI
GROUP BY c.NIF;

答案 1 :(得分:1)

使用SUM()聚合函数并从v.preu子句中删除GROUP BY

SELECT c.NIF,
  SUM(v.preu) preu
FROM CLIENTS c
INNER JOIN RESERVES_VIATGES r
ON c.NIF         = r.NIF_CLIENT
INNER JOIN VIATGES v
ON r.CODI_VIATGE = v.CODI
GROUP BY c.NIF;