[英]Given a set of boolean columns how can I get the top 5 columns with the most amount of true values
CREATE TABLE test(
column1 BOOLEAN,
column2 BOOLEAN,
column3 BOOLEAN
);
INSERT INTO test VALUES (true, false, true);
INSERT INTO test VALUES (true, false, true);
INSERT INTO test VALUES (true, false, false);
INSERT INTO test VALUES (true, false, false);
INSERT INTO test VALUES (true, false, true);
INSERT INTO test VALUES (true, false, true);
我正在尋找我得到的結果
按降序排列的最高 True 數:Column1、Column3、Column2。 具體來說,我需要列的名稱。 知道我該怎么做嗎?
使用UNION ALL
從您的表中獲取只有 2 列的結果集:每列的名稱作為字符串及其值。
然后使用 2 級聚合並使用GROUP_CONCAT()
獲得您想要的結果:
SELECT GROUP_CONCAT(name ORDER BY total DESC) result
FROM (
SELECT name, SUM(col) total
FROM (
SELECT 'column1' name, column1 col FROM test
UNION ALL
SELECT 'column2', column2 FROM test
UNION ALL
SELECT 'column3', column3 FROM test
) t
GROUP BY name
) t;
如果您想要不同行中的列名:
SELECT name, SUM(col) total
FROM (
SELECT 'column1' name, column1 col FROM test
UNION ALL
SELECT 'column2', column2 FROM test
UNION ALL
SELECT 'column3', column3 FROM test
) t
GROUP BY name
ORDER BY total DESC;
請參閱演示。
如果實際上有更多列並且您想要前 5 列的名稱,請替換:
GROUP_CONCAT(name ORDER BY total DESC)
和:
SUBSTRING_INDEX(GROUP_CONCAT(name ORDER BY total DESC), ',', 5)
和:
ORDER BY total DESC
和:
ORDER BY total DESC LIMIT 5
比較返回 0 或 1,具體取決於它是否為真,因此您可以將其結果相加
SELECT * FROM test ORDER BY (column1 = true)+(column2 = true)+(column3 = true) DESC LIMIT 5
第 1 列 | 第 2 列 | 第 3 列 ------: | ------: | ------: 1 | 0 | 1 1 | 0 | 1 1 | 0 | 1 1 | 0 | 1 1 | 0 | 0
db<> 在這里擺弄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.