gpt4 book ai didi

mysql - SQL 计算键值列的唯一组合中的行数

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

给定以下 MySQL 表结构:

CREATE TABLE `order_params`( `order_id` BIGINT(30) NOT NULL, 
`key` VARCHAR(50) NOT NULL, `value` VARCHAR(255) NOT NULL );

还有这个数据:

INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('1', 'browser', 'Firefox'); 
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('1', 'os', 'Windows');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('2', 'browser', 'Firefox');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('2', 'os', 'Windows');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('3', 'browser', 'Firefox');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('3', 'os', 'OSX');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('4', 'browser', 'Safari');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('4', 'os', 'OSX');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('5', 'browser', 'Safari');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('5', 'os', 'OSX');
INSERT INTO `order_params` (`order_id`, `key`, `value`) VALUES ('5', 'version', '5');

如何获得以下结果?

browser Firefox os Windows              2
browser Firefox os OSX 1
browser Safari os OSX 1
browser Safari os OSX version 5 1

右边的数字是匹配唯一键/值组合的记录数。这可能吗?

好的,更新以表明我已经尝试过:

SELECT CONCAT(`key`, `value`), COUNT(*)
FROM order_params
GROUP BY `order_id`, `key`, `value`;

这是结果:

browserFirefox  1
osWindows 1
browserFirefox 1
osWindows 1
browserFirefox 1
osOS X 1
browserSafari 1
osOS X 1

我也试过这个:

SELECT `key`, `value`, COUNT(*)
FROM order_params
GROUP BY `key`, `value`;

产生这个:

browser Firefox  3
browser Safari 1
os OS X 2
os Windows 2

显然,这两个都不是想要的结果。

最佳答案

一种方法是聚合的两个阶段

select browser, os, version, count(*)
from (select order_id,
max(case when `key` = 'browser' then `value` end) as browser,
max(case when `key` = 'os' then `value` end) as os,
max(case when `key` = 'version' then `value` end) as version
from order_params op
group by order_id
) p
group by browser, os, version

如果你真的想要你拥有的字符串,你可以将它们连接在一起:

select concat(coalesce(concat('browser ', browser), ''),
coalesce(concat('os ', os), ''),
coalesce(concat('version ', version), ''), count(*)
from (select order_id,
max(case when `key` = 'browser' then `value` end) as browser,
max(case when `key` = 'os' then `value` end) as os,
max(case when `key` = 'version' then `value` end) as version
from order_params op
group by order_id
) p
group by os, browser, version

关于mysql - SQL 计算键值列的唯一组合中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711621/

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