![](/img/trans.png)
[英]SQL: join 2 tables based on column value and select row values where grouped column value is max
[英]SQL Select row where column has certain length and max value
列_A | 列_B | 列_C |
---|---|---|
值 1 | 111A001 | 一些值 1 |
值 1 | 111A002 | 一些价值 2 |
价值 2 | 112A001 | 一些价值 3 |
价值 2 | 112A002 | 一些价值 4 |
价值 2 | 112A003 | 一些价值 5 |
价值 2 | 112A004 | 一些价值 6 |
价值 3 | 115A001 | 一些价值 7 |
价值 3 | 115A002 | 一些价值 8 |
价值 3 | 115A003 | 一些价值 9 |
价值 4 | 117A | 一些值 10 |
大家好,
我对 SQL 查询有疑问。
从上表中,我想得到一个 output 如下:
列_A | 列_B | 列_C |
---|---|---|
值 1 | 111A002 | 一些价值 2 |
价值 2 | 112A004 | 一些价值 6 |
价值 3 | 115A003 | 一些价值 9 |
未选择值 4,因为在“A”之后的 Column_B 中没有任何内容或没有 3 位数字。 正如您在上表中看到的,值 1 在 B 列中有 2 个值,即 111A001 和 111A002。 我想 select 111A002。 值 2 在 B 列中有 4 个值,112A001 - 112A004,我只想选择 112A004。 所以重点是我想 select column_A 中每个值的最大值(在 column_b 中)。
我尝试使用 max(column_B) 但它只显示值 4、117A、一些值 10。
如果标题不正确,我深表歉意。
也许你正在寻找这样的东西:
select
Column_A,
max(Column_B) as Column_B,
max(Column_C) as Column_C
from d
where length(substring(Column_B,locate('A', Column_B) + 1)) >= 3
group by Column_A
select column_a,
max(column_b),
max(column_c) /* Depends if you want max of column_c or column c value corresponding to the max of column_b - Question wasn't very clear */
from table
where column_b not like '%A___' /* Because you said - "Value 4 is not selected because in Column_B after 'A' there is nothing or it didn't have 3 digit." */
group by column_a
如果您确定可以使用它,“A”之后总会有 3 位数字,如果“A”之前的 3 位数字是 ___A%(根据您发布的数据,这也可能是正确的)
%A%
可能不适合您,因为它还会考虑以“A”结尾的字符串; 而在“A”之后你需要一些东西
更好的是使用 function 像length(column_b) = 7
如果您确定字符串将包含 X 个字符。 不确定您在哪个数据库上。 所以 function 可能会有所不同。 一些数据库有 CHAR_LENGTH() 或 LEN()
编辑:只是澄清 ___ 是 3 个下划线。 想澄清一下,因为它看起来像一条大线
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.