SQL查询使用SELECT中的计算不起作用

时间:2014-07-28 15:34:11

标签: sql

此查询的目的是将延迟订单的百分比计入订单总数。所以这个查询的计算部分只是拉回零。其他一切都有效。我评论下面的部分是拉回零。我做错了什么?

SELECT 

        case LM.DState
        WHEN 'OH' THEN 'OH Order'
        WHEN 'NC' THEN 'NC Order'
        WHEN 'TX' THEN 'TX Order'
        WHEN 'WA' THEN 'WA order'
        Else 'Other' 
        End as 'OrderType',

        count(LM.OrderID) as 'Vol',

        sum(case
            WHEN datediff(day, S.Appt, S.Arrived) > 0 THEN 1
            else 0
            END) as 'TotalLates',

    --PART THAT IS ONLY PULLING ZEROS, SHOULD BE NON-ZERO   
    CAST (
    sum(case WHEN datediff(day, S.Appt, S.Arrived) > 0 THEN 1 else 0 END) 
    / count(LM.OrderID) 
    as decimal(5,2)
    ) *100 as 'OTD%'


FROM ((Customers.dbo.CusOrders as LM WITH (NOLOCK) inner join
    Customers.dbo.CusLocations as S WITH (NOLOCK) on LM.OrderID = S.OrderID) inner join
    Customers.dbo.Loads as L with (NOLOCK) on LM.OrderID = L.OrderID)


WHERE LM.CusCode = 'Domestic'


GROUP BY case LM.DState
        WHEN 'OH' THEN 'OH Order'
        WHEN 'NC' THEN 'NC Order'
        WHEN 'TX' THEN 'TX Order'
        WHEN 'WA' THEN 'WA Order
        Else 'Other' 
    End

1 个答案:

答案 0 :(得分:0)

这是由于整数除法发生的舍入,因为你计算一个百分比,值总是低于1,并且四舍五入到0,你可以通过将分子乘以{{1来解决这个问题。 }}:

1.0

例如:

   CAST (
    sum(case WHEN datediff(day, S.Appt, S.Arrived) > 0 THEN 1 else 0 END)*1.0 
    / count(LM.OrderID) 
    as decimal(5,2)
    ) *100 as 'OTD%'