计数列中数值的位置,使用SQL或DAX。

huangapple go评论58阅读模式
英文:

SQL or DAX Count values in column based on their position

问题

"may I ask you for help?"
"How to count values based on their position?"

可以请您帮忙吗?
如何根据位置来计算值?

"I need to have result like this:"

我需要结果如下:

"x 3"
"y 2"
"x 2"
"y 1"

"Thank you!!!"

谢谢!!!

"I am using this SQL script but it does not work..."

我正在使用这个SQL脚本,但它不起作用...
英文:

may I ask you for help?
How to count values based on their position?

column1
x
x
x
y
y
x
x
y

I need to have result like this:

x   3
y   2
x   2
y   1

Thank you!!!

I am using this SQL script but it does not work...

with test as (
	select *,row_number() over (order by (select null)) as countt
	FROM [vf_test_v02] as t
)
select column1,
	       ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY (select null)) as seqnum
from test 
group by column1,countt
ORDER BY countt

答案1

得分: 1

你应该始终提供排序顺序,否则会浪费宝贵的时间。

你可以在SQL中按照以下方式操作:

CREATE TABLE vf_test_v02
    ("column1" varchar(1))
;
    
INSERT INTO vf_test_v02
    ("column1")
VALUES
    ('x'),
    ('x'),
    ('x'),
    ('y'),
    ('y'),
    ('x'),
    ('x'),
    ('y')
;

8 行受影响
with test as (
    select column1, row_number() over (order by (select null)) as rn
    FROM [vf_test_v02] as t
), LG as (SELECT
   rn, column1, CASE WHEN column1 <> LAG("column1") OVER(order by rn) THEN 1 ELSE 0 END lg
FROM test), SU as (
SELECT 
   column1, SUM(lg) OVER(order by rn) su
FROM LG)
SELECT
   column1, COUNT(*) countt
  FROM SU
  GROUP BY column1, su
英文:

You should always pprovide a sorting order, else it costs precious time.

You can do in SQL following

CREATE TABLE vf_test_v02
    (&quot;column1&quot; varchar(1))
;
    
INSERT INTO vf_test_v02
    (&quot;column1&quot;)
VALUES
    (&#39;x&#39;),
    (&#39;x&#39;),
    (&#39;x&#39;),
    (&#39;y&#39;),
    (&#39;y&#39;),
    (&#39;x&#39;),
    (&#39;x&#39;),
    (&#39;y&#39;)
;

8 rows affected
with test as (
    select column1,row_number() over (order by (select null)) as rn
    FROM [vf_test_v02] as t
), LG as (SELECT
   rn,column1, CASE WHEN column1 &lt;&gt; LAG(&quot;column1&quot;) OVER(order by rn) THEN 1 ELSe 0 END lg
FROM test), SU as (
SELECT 
   column1, SUM(lg) OVER(order by rn) su
FROM LG)
SELECT
   column1, COUNT(*) countt
  FROM SU
  GROUP BY column1,su
column1 countt
x 3
y 2
x 2
y 1

fiddle

huangapple
  • 本文由 发表于 2023年7月31日 22:49:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定