Add a . every 3rd digit/pad with 0 in SELECT

瘦欲@ 提交于 2019-12-11 04:16:34

问题


In an MS Access 2007 project, I have a report with the following Record Source:

SELECT SomeTable.SomeCol FROM SomeTable;

SomeCol should be either 1, 2, 3, 6, or 9 digits long.

Let's take the 3, 6 & 9 first. Say it is 123 - this should remain as 123. If it's 123456, this should be changed to 123.456. If it's 123456789, this should be changed to 123.456.789. If it's 1, or 65, this should be changed to 001 and 065 respectively.

How can I modify my SELECT to perform these changes? If the length is not 1, 2, 3, 6, or 9, the string should remain unmodified.

Thanks!


回答1:


I found a solution, although it's not very pretty.

In reality, SomeTable.SomeCol is a very long string, so it looks much worse on my system. The SELECT is part of a much larger query, with multiple JOIN's, so SomeTable is required. I have a feeling this is the best solution:

SELECT switch(
    len(SomeTable.SomeCol) < 3,
        format(SomeTable.SomeCol, '000'),
    len(SomeTable.SomeCol) = 6,
        format(SomeTable.SomeCol, '000\.000'),
    len(SomeTable.SomeCol) = 9,
        format(SomeTable.SomeCol, '000\.000\.000'),
    true,
        SomeTable.SomeCol
) as SomeCol
FROM SomeTable;



回答2:


I do not know your locale, so I don't know whether numbers default to a stop or a comma:

SELECT IIf(Len([atext])<4,Format([atext],"000"),Replace(Format(Val([atext]),"#,###"),",",".")) AS FmtNumber
FROM Table2 AS t;

You could use a similar format statement without basing your report on a query but make sure you change the name of the control before setting it to a function.



来源:https://stackoverflow.com/questions/12560581/add-a-every-3rd-digit-pad-with-0-in-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!