[英]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.