简体   繁体   English

如何计算多行和同一列中的每个值?

[英]How to count each value in multiple rows and same column?

I have the problem to count the number of each tags.我有计算每个标签数量的问题。

For example:例如:

    tags
0  a,b,c,d
1  a,b
2  c,d
3  a,c

My Expected Results:我的预期结果:

tags   count
  a      3
  b      2
  c      3
  d      2

You can use STRING_SPLIT to achieve this您可以使用STRING_SPLIT来实现这一点

SELECT
value, count(*) as countOfTags
FROM
(
VALUES
(0,  'a,b,c,d')
,(1,  'a,b'    )
,(2,  'c,d'    )
,(3,  'a,c'    )
) as t(id, tags)
CROSS APPLY 
string_split(tags,',')
GROUP BY value;

The result set结果集

+-------+-------------+
| value | countOfTags |
+-------+-------------+
| a     |           3 |
| b     |           2 |
| c     |           3 |
| d     |           2 |
+-------+-------------+

Welcome to StackOverFlow!欢迎使用 StackOverFlow!

Do you have an example of your code?你有你的代码的例子吗? Your tag says "SQL" so that's what I'll assume.您的标签上写着“SQL”,这就是我的假设。 I can't tell much from your question right now as you haven't given us enough info to help.我现在不能从你的问题中看出太多,因为你没有给我们足够的信息来帮助我们。 It would be nice for future questions to add a bit more detail as to what you've tried to do already.对于未来的问题,最好添加更多关于您已经尝试做的事情的细节。

Still, I found this post that's on counting occurrences of column values, so it could answer your question.不过,我发现这篇文章是关于计算列值的出现次数,因此它可以回答您的问题。 You can always edit your questions for clarity if need be!如果需要,您可以随时编辑您的问题以确保清晰!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM