转换SQL

时间:2015-07-03 19:36:43

标签: sql sql-server-2008

我有一些SQL查询输出用于低磁盘空间。它以MB显示,例如1342 MB

我想将其转换为GB,如果可能的话,还可以使用十进制格式(如1.3 GB)。有什么建议?

编辑:我正在使用MS SQL 2008.而且我应该在原帖中给出更多信息。抱歉。这是Lansweeper的报道。以下是当前报告查询。

    Select Top 1000000 tblAssets.AssetID,
  tblAssets.AssetUnique,
  tsysOS.OSname As [OS Name],
  tblAssets.Description,
  tblDiskdrives.Caption As [Partition],
  Cast(Cast(tblDiskdrives.Freespace As bigint) / 1024 / 1024 As numeric) As
  [Free (in MB)],
  Cast(Cast(tblDiskdrives.Size As bigint) / 1024 / 1024 As numeric) As
  [Total Size (in MB)],
  tblDiskdrives.Lastchanged As [last changed],
  tsysOS.Image As icon
From tblAssets
  Inner Join tblDiskdrives On tblAssets.AssetID = tblDiskdrives.AssetID
  Inner Join tblOperatingsystem
    On tblAssets.AssetID = tblOperatingsystem.AssetID
  Inner Join tblComputersystem On tblAssets.AssetID = tblComputersystem.AssetID
  Inner Join tblAssetCustom On tblAssets.AssetID = tblAssetCustom.AssetID
  Inner Join tsysOS On tblAssets.OScode = tsysOS.OScode
Where Cast(Cast(tblDiskdrives.Freespace As bigint) / 1024 / 1024 As numeric) <
  5120 And Cast(Cast(tblDiskdrives.Size As bigint) / 1024 / 1024 As numeric) <>
  0 And tblComputersystem.Domainrole > 1 And tblDiskdrives.DriveType = 3 And
  tblAssetCustom.State = 1

3 个答案:

答案 0 :(得分:1)

select cast(1342/1024.0 as numeric(10,1))

注意:

  • .0表达式末尾的1024.0部分非常重要。没有它,你会得到错误的结果。
  • 施放为numeric(10, 1)可以正确处理四舍五入。

答案 1 :(得分:0)

create function dbo.MbToGbString (@mbValue int) returns varchar (10)
as
begin
    return left (round (@mbValue / 1024.0, 1), 3) + ' GB' 
end
go


select dbo.MbToGbString (1342)

答案 2 :(得分:0)

如果您正在使用PostgreSQL:

select pg_size_pretty( megabyteValue * 1024 * 1024 );