gpt4 book ai didi

mysql - SQL - 获取不同的值及其在组中出现的频率计数

转载 作者:行者123 更新时间:2023-11-29 05:01:29 25 4
gpt4 key购买 nike

我有一个表格数据:

CREATE TABLE SERP (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
s_product_id INT,
search_product_result VARCHAR(255)
);


INSERT INTO SERP(s_product_id, search_product_result)
VALUES
(0, 'A'),
(0, 'B'),
(0, 'C'),
(0, 'D'),
(1, 'A'),
(1, 'E'),
(2, 'A'),
(2, 'B'),
(3, 'D'),
(3, 'E'),
(3, 'D');

数据集如下:

s_product_id    |    search_product_result
___________________________________________
0 | A
0 | B
0 | C
0 | D
-------------------------------------------
1 | A
1 | E
-------------------------------------------
2 | A
2 | B
-------------------------------------------
3 | D
3 | E
3 | D

我需要列出所有不同的 search_product_result 值并计算这些值在 s_product_id 中出现的频率。

必需的输出结果集:

DISTINCT_SEARCH_PRODUCT  |   s_product_id_frequency_count    
------------------------------------------------------------
A | 3
B | 2
C | 1
D | 2 [occurred twice in 3, but counted only once.]
E | 2

这里,A出现在三个 s_product_id : 0, 1, 2, B 两个:0、2,依此类推。

D 在同一组 3 中出现两次,但对于该组只计算一次。

我试过按 search_product_result 分组,但这会在同一组中计算 D 两次

select search_product_result, count(*) as Total from serp group by search_product_result

输出:

search_product_result  |  Total
------------------------------------
A | 3
B | 2
C | 1
D | 3 <---
B | 2

最佳答案

您可以尝试以下 - 使用 count(distinct s_product_id)

select search_product_result, count(distinct s_product_id) as Total 
from serp group by search_product_result

关于mysql - SQL - 获取不同的值及其在组中出现的频率计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com