我有一张桌子,不幸的是,我不能以任何方式改变,必须与我所拥有的一起工作。
mysql表有一个标记为“customer_id”的字段。它有2个带有4值数字的带前缀字母。
EX: BI8392
HE8492
WO1293
如何选择具有特定前缀的最大数值?例如,假设我想选择前缀为HE的最大数字。我该如何选择该值?
绝对赞赏任何帮助。我已经被困了一段时间了。
答案 0 :(得分:4)
由于所有剩余的值都可以填充
SELECT RIGHT(MAX(customer_id), 4) max_val
FROM table1
WHERE customer_id LIKE 'HE%'
确保您根据列名称在customer_id
上有一个索引。 LIKE
很可能会使用它。
这是 SQLFiddle 演示
答案 1 :(得分:2)
SELECT LEFT(customer_id,2) AS PREFIX,
MAX(RIGHT(customer_id,4)) AS MAX
FROM table1
GROUP BY LEFT(customer_id,2)
MySQL 5.5.32架构设置:
CREATE TABLE Table1
(`customer_id` varchar(6))
;
INSERT INTO Table1
(`customer_id`)
VALUES
('DD1234'),
('DD1222'),
('EE2345'),
('EE6789')
;
查询1 :
SELECT LEFT(customer_id,2) AS PREFIX,
MAX(RIGHT(customer_id,4)) AS MAX
FROM table1
GROUP BY LEFT(customer_id,2)
<强> Results 强>:
| PREFIX | MAX |
|--------|------|
| DD | 1234 |
| EE | 6789 |
编辑:
SELECT MAX(RIGHT(customer_id,4)) AS MAX
FROM table1
GROUP BY LEFT(customer_id,2)
WHERE LEFT(customer_id,2) = 'HE'
答案 2 :(得分:1)
使用:
SELECT MAX(RIGHT(customer_id,4)) AS max fROM table_name
WHERE LEFT(customer_id,2)='HE';
答案 3 :(得分:0)
如果你的前缀长度相同,你可以这样做:
实施例
SELECT MID(column_name,start[,length]) FROM table_name;
填写:
SELECT MID(customer_id,2,4) FROM table_name;
答案 4 :(得分:0)
示例数据:
mysql> SELECT * FROM Document;
+--------+-------------+
| DataID | Description |
+--------+-------------+
| 1 | BI8392 |
| 2 | HE8492 |
| 3 | HE8493 |
| 4 | HE8490 |
+--------+-------------+
查询:
SELECT MAX(SUBSTR(Description,3)) FROM Document
WHERE SUBSTR(Description,1,2) = 'HE';
返回:
+----------------------------+
| MAX(SUBSTR(Description,3)) |
+----------------------------+
| 8493 |
+----------------------------+
答案 5 :(得分:0)
在SQL Server中,您可以执行子字符串然后执行ORDER BY,您需要将其强制转换为小数(否则它将按Varchar排序,示例999将大于1000)
SELECT SUBSTRING(MyColumn,3, LEN(MyColumn) - 2 )
FROM dbo.MyTable
ORDER BY CAST(SUBSTRING(MyColumn,3, LEN(MyColumn) - 2 ) as decimal) DESC;
上面的数字3是前缀是2个字符长。 因此,数字2是找到没有前缀的字符串长度。