gpt4 book ai didi

sql - 如何在 Postgres 中使用别名创建嵌套的 SELECT COUNT

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

我正在为我的 Postgres 数据库编写以下 SQL 查询:

SELECT(
(SELECT count(*) as A FROM merchant WHERE nome LIKE 'A%'),
(SELECT count(*) as B FROM merchant WHERE nome LIKE 'B%'),
(SELECT count(*) as C FROM merchant WHERE nome LIKE 'C%'),
(SELECT count(*) as D FROM merchant WHERE nome LIKE 'D%'),
(SELECT count(*) as E FROM merchant WHERE nome LIKE 'E%'),
(SELECT count(*) as F FROM merchant WHERE nome LIKE 'F%'),
(SELECT count(*) as G FROM merchant WHERE nome LIKE 'G%'),
(SELECT count(*) as H FROM merchant WHERE nome LIKE 'H%'),
(SELECT count(*) as I FROM merchant WHERE nome LIKE 'I%'),
(SELECT count(*) as J FROM merchant WHERE nome LIKE 'J%'),
(SELECT count(*) as K FROM merchant WHERE nome LIKE 'K%'),
(SELECT count(*) as L FROM merchant WHERE nome LIKE 'L%'),
(SELECT count(*) as M FROM merchant WHERE nome LIKE 'M%'),
(SELECT count(*) as N FROM merchant WHERE nome LIKE 'N%'),
(SELECT count(*) as O FROM merchant WHERE nome LIKE 'O%'),
(SELECT count(*) as P FROM merchant WHERE nome LIKE 'P%'),
(SELECT count(*) as Q FROM merchant WHERE nome LIKE 'Q%'),
(SELECT count(*) as R FROM merchant WHERE nome LIKE 'R%'),
(SELECT count(*) as S FROM merchant WHERE nome LIKE 'S%'),
(SELECT count(*) as T FROM merchant WHERE nome LIKE 'T%'),
(SELECT count(*) as U FROM merchant WHERE nome LIKE 'U%'),
(SELECT count(*) as V FROM merchant WHERE nome LIKE 'V%'),
(SELECT count(*) as W FROM merchant WHERE nome LIKE 'W%'),
(SELECT count(*) as X FROM merchant WHERE nome LIKE 'X%'),
(SELECT count(*) as Y FROM merchant WHERE nome LIKE 'Y%'),
(SELECT count(*) as Z FROM merchant WHERE nome LIKE 'Z%')
)

输出是名为“行”的一列,内容如下:

(26,20,28,13,15,9,13,16,13,1,0,13,20,7,10,20,0,17,44,25,3,8,7,1,2,2)

我应该得到 26 行(根据我的别名命名为“A”、“B”等...)以及相关总数。为什么它给我一行?

如果我通过 PHP var_dump 读取它,输出如下:

string(68) "(26,20,28,13,15,9,13,16,13,1,0,13,20,7,10,20,0,17,44,25,3,8,7,1,2,2)"

怎么了?我犯了什么错误还是与 Postgres 相关?

最佳答案

您想为每个字符创建一个单独的行。一种方法是生成所有字符,然后按它们聚合。这是一种方法:

select chr(chars.c + ascii('A')) as c,
sum(case when ascii(left(m.nome, 1)) = chars.c + ascii('A') then 1 else 0 end)
from generate_series(0, 25) as chars(c) cross join
merchant m
group by c;

编辑:

Alan 的建议是一个更好的查询:

select chr(chars.c + ascii('A')) as c,
count(m.nome)
from generate_series(0, 25) as chars(c) left join
merchant m
on ascii(left(m.nome, 1)) = chars.c + ascii('A')
group by c;

关于sql - 如何在 Postgres 中使用别名创建嵌套的 SELECT COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084359/

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