Sql server 2005 修改sql server 2005中计数的整数结果

Sql server 2005 修改sql server 2005中计数的整数结果,sql-server-2005,count,Sql Server 2005,Count,我正在使用SQLServer2005,我正在从一个特定的表中进行计数 SELECT count(StudentIdReference) as studentCount FROM StudentTable 现在这个select语句正在返回类似于2、78或790的结果。但在未来,它将迅速增长,在用户界面上,我没有足够的空间来显示像1000000这样的数字。 我想要的是,在3位数之后,我将得到1K或1.6K这样的数字,就像我们在stackoverflow上看到的那样。您需要编写自己的逻辑来显示这样的

我正在使用SQLServer2005,我正在从一个特定的表中进行计数

SELECT count(StudentIdReference) as studentCount FROM StudentTable
现在这个select语句正在返回类似于2、78或790的结果。但在未来,它将迅速增长,在用户界面上,我没有足够的空间来显示像1000000这样的数字。
我想要的是,在3位数之后,我将得到1K或1.6K这样的数字,就像我们在stackoverflow上看到的那样。

您需要编写自己的逻辑来显示这样的文本。没有内置的方法。

我将从SQL Server按原样返回计数,并将格式设置留给UI。这是因为:
1) 在SQL之外进行格式化/字符串操作通常更容易/更有效
2) 使用同一查询的代码中的不同位置可能希望以不同的方式使用数据(可能不是现在,但将来可能会这样),因此按原样返回计数会给您带来灵活性,即不需要一个版本以INT形式返回计数,另一个版本以格式化的VARCHAR形式返回计数


您可以在SQL中执行此操作,但一般来说,我认为应该将其推送到UI中,因为这是一种显示/格式化行为。

在应用程序的表示层中执行此操作会更简单

您可以编写一个用户函数并执行如下操作

CREATE FUNCTION prettyPrint 
(@number int)
RETURNS varchar(30)
AS
BEGIN
declare @return varchar(30)
set @return = cast(@number as varchar(3))
if @number > 1000
    set @return = ''+ cast((@number/1000) as varchar(3)) + '.' + cast((@number % 1000)/100 as varchar(3)) +'K'

-- here must be more 'exceptions' or change all this about the magic number 1000
return @return
end

select dbo.prettyPrint(1500)

SELECT prettyPrint(count(StudentIdReference)) as studentCount FROM StudentTable

正如其他人所说,您确实应该在表示层而不是在数据库中这样做,但是,这将为您做到:

Declare @StudentCount int,
        @StudentCountFormatted varchar(10)

Select @StudentCount = Count(StudentIdReference) as studentCount FROM StudentTable


If @StudentCount > 999
    Begin

        Select @StudentCountFormatted = Convert(Varchar(10), Convert(numeric(19,1), (@StudentCount/ 1000.00))) + 'K'

    End
Else
    Begin
        Select @StudentCountFormatted = @StudentCount
    End


Select @StudentCountFormatted

你可以试试这样的东西

SELECT 
    CASE 
    WHEN len(cast(count(*) as varchar(10)))< 4 then cast(count(*) as varchar(10))
    WHEN len(cast(count(*) as varchar(10)))> 4 and len(cast(count(*)as varchar(10)))< 7 
            THEN cast(cast(count(*) / 1000.0 as decimal(10,1)) as varchar(10)) + 'k' 
    ELSE  cast(cast(count(*) / 1000000.0 as decimal(10,1)) as varchar(10)) + 'm'    
END StudentCount
FROM StudentTable
选择
案例
当len(cast(count(*)为varchar(10))小于4时,则cast(count(*)为varchar(10))
当len(cast(count(*)为varchar(10))大于4且len(cast(count(*)为varchar(10))小于7时
然后将(cast(count(*)/1000.0转换为十进制(10,1))转换为varchar(10))+'k'
ELSE cast(cast(count(*)/1000000.0作为十进制(10,1))作为varchar(10))+'m'
期末学生人数
从学生桌

在表示层而不是数据库中处理格式要求。@Joe Stefanelli您能告诉我怎么做吗。我的意思是,如果我得到像1009090的整数,我将如何转换它?你能建议我如何实现它吗?我是说我要写什么逻辑?