【问题标题】:How can we join the results with GROUP BY我们如何使用 GROUP BY 加入结果
【发布时间】:2020-01-15 23:44:17
【问题描述】:

我在这里加入三个表,并希望通过方法按组获取结果。当我这样编写查询时

$query=$this->db->query("SELECT p.id, p.customerid, T.u_id, A.u_id, T.agent_name,
       P.date as d_date, T.total_profit, A.t_price, A.t_dc
  FROM bills P
  LEFT JOIN((SELECT *,
                    bill_details.id as b_id,
                    bill_details.user_id as u_id,
                    SUM(bill_details.profit) AS total_profit
               FROM bill_details
              WHERE DATE(bill_details.bill_date) BETWEEN '{$start_date}' AND
                    '{$end_date}'
                AND bill_details.user_id = 406
              GROUP BY Date(bill_details.bill_date), bill_details.user_id) T)
    ON p.id = T.bill_id
  LEFT JOIN((SELECT *,
                    assigned_result.assigned_result_id as a_id,
                    assigned_result.user_id as u_id,
                    SUM(assigned_result.total_price) AS t_price,
                    SUM(assigned_result.total_dc) AS t_dc
               FROM assigned_result
              WHERE DATE(assigned_result.date) BETWEEN '{$start_date}' AND
                    '{$end_date}'
                AND assigned_result.user_id = 406
              GROUP BY Date(assigned_result.date), assigned_result.user_id) A)
    ON p.id = A.bill_no
 WHERE T.u_id = 406
    OR A.u_id = 406");
  return $query->result();

如果我在做这样的 group_by 条件GROUP BY T.u_id,A.u_id 我的输出看起来像这样

Name    Date          Purchase      Winning     Balance

        2019-07-25                    240        -240

Ned     2019-07-25     132.60        0.00         132

我希望结果是这样的

Name    Date          Purchase      Winning     Balance

Ned     2019-07-25    132.60          240          132

【问题讨论】:

    标签: mysql sql group-by aggregation


    【解决方案1】:

    使用额外的max() 聚合:

    SELECT max(Name) as Name, Date, max(Purchase) as Purchase, 
           max(Winning) as Winning, max(Balance) as Balance
      FROM
      (
       <YourOriginalQuery>
      ) q
     GROUP BY Date;
    

    【讨论】:

      【解决方案2】:

      您没有使用GROUP BY 显示查询。但是根据您的描述,您可以执行以下任一操作:

      • 完全删除GROUP BY。聚合查询将返回一行。
      • 使用 `GROUP BY COALESCE(T.u_id, A.u_id)

      如果这些列在SELECT 中,您可能还需要调整SELECT 子句。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-13
        • 1970-01-01
        • 1970-01-01
        • 2011-10-12
        相关资源
        最近更新 更多