如何通过SQL中的列获得最大值组

发布于 2025-02-09 10:34:16 字数 716 浏览 1 评论 0原文

大家好,大家好,我在这里问,目前我正在尝试按照表面的预期获得总数。总数量将通过数据列自动计算总数量组,直到将数据更改为其他数据的

先前结果:

Id   Name      Data        
----------------------------
1    A       A_data_1          
2    A       A_data_2         
3    A       A_data_3          
4    B       B_data_1        
5    B       B_data_2           
6    C       C_data_1           

预期结果:

Id   Name      Data        Total Quantity
-----------------------------------------
1    A       A_data_1          null
2    A       A_data_2          null
3    A       A_data_3            3
4    B       B_data_1          null
5    B       B_data_2            2
6    C       C_data_1            1

我尝试使用组,但似乎对我不起作用

Hi and good day everyone, i'm here to ask currently i'm trying to get total quantity as expect below table. The total quantity will auto calculate the total quantity group by data column until the data is changed to others data

Previous Result:

Id   Name      Data        
----------------------------
1    A       A_data_1          
2    A       A_data_2         
3    A       A_data_3          
4    B       B_data_1        
5    B       B_data_2           
6    C       C_data_1           

Expected Result:

Id   Name      Data        Total Quantity
-----------------------------------------
1    A       A_data_1          null
2    A       A_data_2          null
3    A       A_data_3            3
4    B       B_data_1          null
5    B       B_data_2            2
6    C       C_data_1            1

I have try to use group by but it seems not working for me

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦罢 2025-02-16 10:34:16

对于预期的结果,您需要使用左JON与子查询,该子查询获得每个组的总数。

尝试:

   select test.id,test.name,test.`data`,total_count
   from test
   left join ( select max(id) as id ,name,count(name) as total_count
                from test 
                group by name  
              ) as t1 on t1.id=test.id;

https:///wwwwww.db-fiddle.com/fidb-fiddle.com/ /a>

For the expected result you need to use left join with the subquery which get the total count for each group.

Try:

   select test.id,test.name,test.`data`,total_count
   from test
   left join ( select max(id) as id ,name,count(name) as total_count
                from test 
                group by name  
              ) as t1 on t1.id=test.id;

https://www.db-fiddle.com/f/uLPPE1DoKjKYBoSXfKahJN/28

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文