2

我有一张Daily_account桌子:

customer_id    account_id            current_balance

1                 D1                       200
2                 d2                       300
3                 d10                      400
4                 d100                     500
5                 d101                     600

现在我有一个查询:

select customer_id,account_id,current_balance
from daily_account
where account_id between 'D1' and'D100'

它给了我 D1、D10、D100 账号的输出,但我想得到每个账号的输出。如何获得 D1 和 d100 之间的每个帐户的输出?

4

6 回答 6

1

经过更多研究后,我发现一个函数是 cast 函数,它给了我答案....

select  customer_id, account_id,current_balance  from daily_account 
where cast(right(Account_id,(length(account_id)-1)) AS unsigned) 
between '1' and'100'
于 2012-11-05T05:36:11.020 回答
1

上述代码段中的 between 语句使用的是字符串,这与数字排序不同。

如果 account_id 总是以“D”开头,我们可以将其删除并将其转换为一个数字:

SELECT *
, REPLACE(account_id, 'd','0') // just replace
, CAST( REPLACE(account_id, 'd','0') as int) // now convert to int
FROM daily_account

并在两者之间使用它,像这样使用它

SELECT customer_id,account_id,current_balance
FROM daily_account
WHERE 
CAST( REPLACE(account_id, 'd','0') as int) between 1 and 100
于 2012-11-05T05:37:40.657 回答
1

如果一切都以一个字符开始,您可以执行以下操作:

SELECT * FROM (
SELECT customer_id
     , CAST(REPLACE(account_id,'d','') AS int) account_id
     , current_balance
FROM daily_account) tbl
WHERE account_id between '1' and'100'
于 2012-11-05T05:38:05.520 回答
1

一个技巧是像这样删除 account_id 中的非数字:

SELECT * FROM Daily_account WHERE CAST(REPLACE(account_id,'D','') AS INT) BETWEEN 1 AND 10
于 2012-11-05T05:38:12.127 回答
1
select customer_id,account_id,current_balance
from daily_account
where CAST(replace(account_id, 'D', '') as int) between 1 and 100
于 2012-11-05T05:39:06.220 回答
0

您的回答似乎暗示您希望解决方案可以使用各种前缀,而不仅仅是'D'. 如果是这种情况,请考虑以下替代方案:

SELECT customer_id, account_id, current_balance
FROM daily_account
WHERE STUFF(account_id, 1, 1, '') between 1 and 100
;

以上是 SQL Server,但由于您的回答似乎也暗示您正在使用 MySQL,因此这里有一个 MySQL 等价物:

SELECT customer_id, account_id, current_balance
FROM daily_account
WHERE INSERT(account_id, 1, 1, '') between 1 and 100
;
于 2012-11-05T06:40:51.887 回答