How to put a counter in Group By Customer(如何在按客户分组中放置计数器)
问题描述
它们是同一列
Name-Category
A-SL
B-SL
C-SL
A-SL
A-SL
C-SL
现在在我的脚本中,我将它们分组到类别中,但我想计算它们在查询中出现的次数.请看下面:
now in my script, i group them in Category but i want to count on how many times they occur in the query. please see below:
Customer-Line#
A-1 (means its the first time it occurs)
A-2 (means its the second time it occurs)
A-3 (means its the third time it occurs)
....so on
----------
B-1 (means its the first time it occurs)
----------
C-1 (means its the first time it occurs)
C-2 (means its the second time it occurs)
抱歉造成混乱,希望大家都清楚.
sorry for confusion, hope its clear for everyone.
谢谢,
推荐答案
您可以使用 row_number()
给同名的客户添加一个数字:
You can use row_number()
to add a number to customers with the same name:
select name + '-' + cast(row_number() over (
partition by name order by id) as varchar(24))
from YourTable
如果只有在有多个客户时才需要号码,您可以使用 case when ... then ... end
表达式:
If the number is only required if there is more than one customer, you can use a case when ... then ... end
expression:
select name +
case
when count(*) over (partition by name) = 1 then ''
else '-' + cast(row_number() over (
partition by name order by id) as varchar(24))
end
from YourTable
SQL Fiddle 示例.
这篇关于如何在按客户分组中放置计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在按客户分组中放置计数器


基础教程推荐
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01