如何获得箱子尺寸的总重量,例如12 x 160g 等于 1.92kg

问题描述

不确定这是否可能。

但是,假设我在表格中有这样一列:

12 x 60g
12 x 160g
500g
1kg
1kg
12 x 160g
12 x 250g

有些是个人尺寸,有些是箱子尺寸。

是否可以获取每行的总重量?如果是这样,会怎么做?

例如

0.72kg  /* 12 x 0.060 = 0.72 */
1.92kg  /* 12 x 0.160 = 1.92 ... */
0.5kg
1kg
1kg
1.92kg
3kg

解决方法

添加到@Tomalak 的评论中,下面是一个示例脚本,您可以使用它来填充权重表达式转换表。

loading==false?yourui():loading()
,

计算流量公斤数的函数:

CREATE FUNCTION dbo.computeWeightKg(@weight NVARCHAR(50))
RETURNS NUMERIC
AS
BEGIN
    DECLARE @Result NUMERIC = 0; 
    DECLARE @Divider INT = 1;
    DECLARE @xIndex INT = NULL;

    IF (RIGHT(@weight,2) = 'kg')
    BEGIN
        SET @weight = SUBSTRING(@weight,1,LEN(@weight) - 2);
    END ELSE BEGIN
        SET @weight = SUBSTRING(@weight,LEN(@weight) - 1);
        SET @Divider = 1000;
    END

    SET @xIndex = CHARINDEX('x',@weight)

    IF @xIndex = 0
    BEGIN
        SET @Result = CAST(@weight AS NUMERIC)
    END ELSE BEGIN
        DECLARE @x1 NVARCHAR = SUBSTRING(@weight,@xIndex - 1);
        DECLARE @x2 NVARCHAR = SUBSTRING(@weight,@xIndex + 2,50);

        SET @Result = CAST(@x1 AS NUMERIC) * CAST(@x2 AS NUMERIC);
    END

    RETURN @Result / @Divider;
END;
,

我假设列的格式与您提供的格式非常相似,例如 kg 或 g,以及一个或两个由 x 分隔的数字,并且可能有空格:>

12 x 60g
12 x 160g
500g
1公斤
12 x 250g

因此我们可以创建一个内联函数来使用一系列 APPLY 来完成所有这些计算。:

CREATE FUNCTION GetCalculatedWeight
    (@val varchar(20))
RETURNS TABLE WITH SCHEMABINDING
AS RETURN
(
SELECT
    Result = v3.FirstNum * v3.SecondNum / v2.Factor

FROM
-- Remove spaces
    (SELECT Val = REPLACE(@val,' ','') ) v1
-- Get division factor and position of 'x'
OUTER APPLY (SELECT
    factor = CASE WHEN @val LIKE '%kg' THEN 1 ELSE 1000 END,toTakeOff = CASE WHEN @val LIKE '%kg' THEN 2 ELSE 1 END,x = CHARINDEX('x',v1.Val)
) v2

OUTER APPLY (SELECT
    FirstNum = TRY_CAST(
        CASE WHEN v2.x = 0 THEN
            LEFT(v1.Val,LEN(v1.Val) - v2.toTakeOff)
        ELSE
            LEFT(v1.Val,v2.x - 1)
        END
        AS int),SecondNum = CASE WHEN v2.x > 0 THEN
            TRY_CAST(SUBSTRING(v1.Val,v2.x + 1,LEN(v1.Val) - v2.toTakeOff - v2.x - 1) AS int)
        ELSE 1
        END
) v3

)

您可以通过APPLY将它放到您的桌子上来使用它:

SELECT t.*,Weight = wt.Result
FROM table t
CROSS APPLY dbo.GetCalculatedWeight (t.Weight) wt

如果您有小数,则将 TRY_CAST 替换为 intdecimal