【问题标题】:How to sum when they have same color with sql?当它们与sql具有相同的颜色时如何求和?
【发布时间】:2019-01-16 17:21:43
【问题描述】:

我有这张桌子

我想忽略 productNo 并相应地汇总所有产品计数。

select sum(count), max(productNo) 
from Table 
where date between 117 and 118 
group by product

这个给出了错误的结果...

我想要每个 Product-ProductNo 组合的计数总和

【问题讨论】:

  • 您的问题没有解释为什么您的查询包含 max(productNo)
  • 标记您正在使用的 DBMS(即MySQLSQL Server 等)。
  • MySql,我现在肯定会标记
  • 因为我只想得到一个产品,没有每个日期

标签: mysql sql


【解决方案1】:

尝试如下

 select product,productno,sum(count) as result
 from table_name
 where productno='X1'
 group by product,productno

【讨论】:

    【解决方案2】:

    似乎您需要按结果排序的第一行

    select product,productno,sum(count) as result
    from table
    group by product,productno
    order by result 
    limit 1 
    

    【讨论】:

    • 我只想得到一个产品 没有一个特定产品每天计数,无论哪个产品编号。
    • 更新您的问题添加您的实际查询..您的实际结果(连贯的数据样本)和预期结果..作为文本数据(不是图像)
    【解决方案3】:

    由于您没有标记任何DBMS,所以我会使用row_number()

    select t.*
    from (select product, productno, sum(count) as cnt,
                 row_number() over (partition by product order by sum(count) desc) as seq
          from table t
          group by product, productno
         ) t
    where seq = 1;
    

    您也可以使用LIMIT 子句(但不是针对每个产品):

    select product, productno, sum(count) as cnt
    from table t
    group by product, productno
    order by cnt desc
    limit 1; 
    

    其他一些 DBMS 需要 TOP 子句而不是 LIMIT 子句,因此您可以进行相应更改,但想法是相同的。

    【讨论】:

      【解决方案4】:
      select sum(count), max(productNo) 
      from Table 
      where date between 117 and 118 
      group by product, productNo 
      

      这样就可以了:)

      【讨论】:

      • 请解释它为什么以及如何工作,以便知识较少的人能够理解和重用此代码示例:-)
      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2022-11-11
      • 2018-07-17
      相关资源
      最近更新 更多