嵌套聚合/分组

时间:2016-07-08 09:08:14

标签: sql sql-server

我有这个:

SELECT A.salesperson, A.TDP, A.Units, T.new_target as Target
FROM 
(
    SELECT a.new_salespersonidname as Salesperson, 
           a.new_salespersonid, 
           SUM(b.new_profits_sales_totaldealprofit) as TDP, 
           COUNT (a.new_dealsheetid) as Units 
    FROM new_dealsheet a 
        LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid 
    WHERE MONTH(a.New_actualdate) = 7
      AND YEAR(a.new_actualdate) = 2016
      AND a.New_PassedToAdmin = 1 
    GROUP BY a.new_salespersonidname, a.new_salespersonid
) A 
LEFT JOIN new_salespersontarget T
    on  T.new_salespersonid = A.new_salespersonid
    AND T.new_month = 7 and T.new_year = 2016 AND T.new_type = 2
ORDER BY A.TDP desc

这样可以正常工作,并为我提供一个月(2016年7月)的总销售额以及该月的销售人员目标。

我需要第二个版本,它向我展示2016年。所以我可以轻松改变:

WHERE MONTH(a.New_actualdate) = 7 AND YEAR(a.new_actualdate) = 2016

为:

 WHERE YEAR(a.new_actualdate) = 2016

但是,我能获得所有2016年目标的总和吗?

由于

1 个答案:

答案 0 :(得分:0)

只是分组

// I am assuming you have session_start(); included in common.php 
require("common.php"); 

if(!empty($_POST)) { 
    if(isset($_POST['validEmail'])) {
        $query = "SELECT *
               FROM registered_email 
               WHERE email = :validEmail"; 
        $query_params = array( ':validEmail' => $_POST['validEmail'] ); 
        try { 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) { 
            die("Failed to run query");
        } 
        $login_ok = false; 
        $row = $stmt->fetch(); 
        if($row) { 
            if($_POST['validEmail'] === $row['email']) { 
                $login_ok = true; 
            } 
        } 
        if($login_ok) { 
            $_SESSION['sesEmail'] = $row; 
            if (isset($_POST['validEmail'])) {
                // the page where you are redirecting should be linked with session as well
                echo "<script>window.location.href='http://www.url.com.ph/some.php'</script>";
            } 
        } else  { 
            // Tell the user they failed 
            print "Sorry to say that your Email is not Registered!."; 
        } 
    }
    else  { 
        // Tell the user they failed 
        print "Sorry no POST parameters!."; 
    }
}