[英]T-SQL : count occurrences per unique substring in a column
I want to count occurrences per unique substring in a column.我想计算列中每个唯一 substring 的出现次数。
SELECT DISTINCT LEFT(code, 3)
FROM table-with-codes
Output: Output:
code
------------------
VJCrandomthings
PASrandomthings
CAArandomthings
PASrandomthings2
PASrandomthings3
Expected output:预期 output:
caa 1
pas 3
vjc 1
I tried我试过了
SELECT COUNT(DISTINCT LEFT(code, 3))
FROM table-with-codes
but that returns 3 as result.但这会返回 3 作为结果。
You need to count
with group by
你需要用group by
来count
select Left(code,3), Count(*)
from [table-with-codes]
group by Left(code,3)
You are correct with using left
but instead of distinct
you should group by
您使用left
是正确的,但您应该group by
而不是distinct
declare @table_with_codes table (code varchar(50))
insert into @table_with_codes values ('VJCrandomthings'), ('PASrandomthings'), ('CAArandomthings'), ('PASrandomthings2'), ('PASrandomthings3')
select left(code, 3) as code_3,
count(*) as cnt
from @table_with_codes
group by left(code, 3)
how this works这是如何工作的
By using the group by you can count all rows that are grouped (and thus only returned once in the result), in this case all rows with the same value in lef(col, 3)通过使用 group by,您可以计算所有分组的行(因此在结果中只返回一次),在这种情况下,所有行在 lef(col, 3) 中具有相同的值
The result will be结果将是
code_3 cnt
------ ---
CAA 1
PAS 3
VJC 1
You should keep the extracted 3 letters in the select
statement and Group by
.您应该将提取的 3 个字母保留在select
语句和Group by
中。
Query询问
Select left(code, 3) as code3, count(left(code, 3)) as cnt
From tablename
Group by left(code, 3)
Order by 1;
I don't like having LEFT(code, 3) appear more than once in the query.我不喜欢 LEFT(code, 3) 在查询中多次出现。 To improve maintainability and readability I'd refactor it using CROSS APPLY, like this:为了提高可维护性和可读性,我会使用 CROSS APPLY 对其进行重构,如下所示:
SELECT subcode, COUNT(*)
FROM table-with-codes
CROSS APPLY (SELECT LEFT(code, 3)) AS T(subcode)
GROUP BY subcode
You can use Common Transaction Expression to avoid mentioning left function two times:您可以使用Common Transaction Expression避免两次提及 left function:
create table [table-with-codes] (code nvarchar(100))
go
insert into [table-with-codes] values('VJCrandomthings'),('PASrandomthings'),('CAArandomthings'),('PASrandomthings2'),('PASrandomthings3');
with cte as (select LEFT(code,3) mycode from [table-with-codes])
select mycode,count(1) N from cte group by mycode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.