t-sql来拆分列结果并对结果进行计算

xoshrz7s  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(307)

我有一张表,里面有这么多文件

FileSize
68 bytes
122.80 Kb
23.5 Mb
1.2 Gb

我需要选择以mb为单位的结果,所以结果看起来像

Converted FileSize
0.000068
0.1228
23.5
1200

这样可以正确地将结果拆分

WITH Splitted AS
(
    SELECT CAST(N'<x>' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([File Size],N' ',N' '),N'&',N'&amp;'),N'<',N'&lt;'),N'>',N'&gt;'),N' ',N'</x><x>') + N'</x>' AS XML) testXML
    FROM Attachment
)
SELECT testXML.value('/x[1]','float') AS Number
      ,testXML.value('/x[2]','nvarchar(max)') AS metric
FROM Splitted

Size      Metric
68        bytes
122.8     Kb
23.5      Mb      
1.2       Gb

有没有办法在sql中基于“metric”列值对“size”列值进行转换?

insrf1ej

insrf1ej1#

一种方法是 CHARINDEX 获取空间的位置并将值拆分为两列。然后你用一个 CASE 表达式将值乘以适当的量:

WITH YourTable AS(
    SELECT V.FileSize
    FROM (VALUES('68 bytes'),
                ('122.80 Kb'),
                ('23.5 Mb'),
                ('1.2 Gb'))V(FileSize))
SELECT *,
       V.[Size] * CASE V.Metric WHEN 'bytes' THEN 1. / (1024 * 1024)
                                WHEN 'Kb' THEN 1. / 1024
                                WHEN 'Mb' THEN 1
                                WHEN 'Gb' THEN 1024
                  END AS Megabytes
FROM YourTable YT
     CROSS APPLY(VALUES(TRY_CONVERT(decimal(10,4),LEFT(YT.FileSize,NULLIF(CHARINDEX(' ',YT.FileSize),0)-1)),STUFF(YT.FileSize,1,NULLIF(CHARINDEX(' ',YT.FileSize),0),'')))V(Size,Metric)
euoag5mw

euoag5mw2#

根据上面我标记的答案,这就是我所用的。

SELECT [File Type], [File Size],
      CAST( A.Size * CASE A.Metric WHEN 'bytes' THEN 1.0 / (1024 * 1024)
                                WHEN 'Kb' THEN 1.0 / 1024
                                WHEN 'Mb' THEN 1
                                WHEN 'Gb' THEN 1024
                  END as NUMERIC(10, 2))AS Megabytes
FROM Attachment AA
     CROSS APPLY(
        VALUES( TRY_CONVERT(decimal(10,4),LEFT(AA.[File Size], NULLIF(CHARINDEX(' ',AA.[File Size]),0)-1)),
            STUFF(AA.[File Size],1,NULLIF(CHARINDEX(' ',AA.[File Size]),0),''))
        )A (Size, Metric)

WHERE AA.[File Type] IS NOT NULL
ORDER BY Megabytes ASC
File type   File size   Megabytes
txt         68 bytes    0.00
txt         68 bytes    0.00
PDF         122.80 KB   0.12
PDF         122.80 KB   0.12
txt         23.5 Mb     23.50
PDF         1.2 Gb      1228.80

相关问题