【问题标题】:How to use GroupBy correctly from multiple joined table如何从多个连接表中正确使用 GroupBy
【发布时间】:2017-05-23 03:35:45
【问题描述】:

我有下表imagetable...

这是我的查询...

SELECT w.name as wholesaler_name,
       w.outlet_id,
       w.distributor_name,
       w.distributor_id,
       wt.name as tipe_plus,
       v.target,
       v.week as periode,
       SUM(v.total_transaction),
       v.rebate,
       v.total_voucher
FROM voucher v
JOIN wholesalers w ON w.id=v.wholesaler_id
JOIN wholesaler_types wt ON w.wholesaler_type_id=wt.id
GROUP BY w.name,
         w.outlet_id,
         w.distributor_name,
         w.distributor_id,
         wt.name,
         v.target,
         v.week,
         v.rebate,
         v.total_voucher;

periode一栏,有一个wholesaler_name有一个2,同时期(11.2017)。我想要这样,如果发生这种情况,total_transaction 列将变为SUM()

我使用GROUP BY,但结果还是一样。

希望你能帮忙。

谢谢。

【问题讨论】:

    标签: mysql sql database orm


    【解决方案1】:

    chek total_vouchers 专栏。

    在您的查询中,如果total_vouchers11.2017 相同,则一切都可以,因为您的查询最后一步将需要按total_vouchers 分组,在您的结果链接中我看不到total_vouchers,如果它们不是11.2017 相同,然后从 group by 中排除该列,然后在 select 部分中选择或将该列放入 Sum()、Count()....(聚合函数)中

    【讨论】:

    • 我明白了,我意识到 11.2017 中的 total_voucher 有所不同,现在我更改为 sum(total_voucher) 并删除 group by 中的 total_voucher 及其工作。谢谢你。 :)
    【解决方案2】:

    您可以使用子查询来简化您的 sql 语句。

    select * from
    (
        SELECT yourPK, v.week as periode, sum(v.total_transaction)
        FROM voucher v
        JOIN wholesalers w ON w.id=v.wholesaler_id
        JOIN wholesaler_types wt ON w.wholesaler_type_id=wt.id
       GROUP BY yourpk, periode
    ) SumResult
    join TheOthersTable on SumResult.yourPK = TheOthersTable.yourPK
    

    【讨论】:

      【解决方案3】:

      检查结果中的其他列。 例如,如果一个列

      【讨论】:

        猜你喜欢
        • 2019-11-02
        • 1970-01-01
        • 1970-01-01
        • 2012-06-25
        • 1970-01-01
        • 2020-04-23
        • 2011-07-23
        • 2010-10-08
        • 2011-09-09
        相关资源
        最近更新 更多