设置等于表达式的新变量时,列名无效

时间:2019-04-04 15:40:21

标签: sql sql-server

我需要根据查询中的两列计算百分比,并将该数字存储在新变量中。当我将变量设置为等于表达式时,出现“无效的列名”错误。

SELECT
Count(Case When HMC_Place_Position is null Then 0 end) as Parts,
COUNT(*) AS Total_Parts,                                                                        /*Total Parts */

COUNT(CASE
    WHEN Outfeed_Place_Time IS NOT NULL THEN 1      
END) AS Total_Good_Parts                                                                        /*Total Good Parts */

FROM PartData_GKN05_C
WHERE Infeed_Pick_Time >= DATEADD(day,-7, GETDATE()) 
ALTER TABLE  PartData_GKN05_C Add Total_Good_Parts int
DECLARE @Total_Good_Percent AS float = ((Total_Good_Parts / Total_Parts)*100)

2 个答案:

答案 0 :(得分:1)

我相信您希望从PartData_GKN05_C中的零件记录总数中获取“好”零件的百分比。

因此,使用您对“好零件”的定义(Outfeed_Place_Time不为空),以下查询将对这些零件进行计数,然后除以表中所有零件记录的计数。

由于“ count()”返回一个整数值,因此在对它们进行除法之前,必须将其中一个“ count()”强制转换为浮点数,以使SQL不会返回零(因为“ int / int”不会浮点数返回小数)。

我们只需要转换一个“ Count()”,因为SQL会隐式转换另一个,但是如果您愿意,可以随意将它们都转换为显式浮点数。

这是代码:

DECLARE 
    @Total_Good_Percent float

SELECT
    @Total_Good_Percent =   (
                                COUNT(
                                    CASE
                                        WHEN Outfeed_Place_Time IS NOT NULL
                                            THEN 1
                                        END
                                )
                                /convert(float,count(*))
                            )*100
FROM 
    PartData_GKN05_C
WHERE 
    Infeed_Pick_Time >= DATEADD(day, -7, GETDATE());

select
    @Total_Good_Percent

答案 1 :(得分:0)

尝试此代码:

DECLARE @Total_Good_Parts INT, @Total_Parts INT;
SELECT
--Count(Case When HMC_Place_Position is null Then 0 end) as Parts,
@Total_Parts = COUNT(*), 
@Total_Good_Parts = COUNT(CASE
                              WHEN Outfeed_Place_Time IS NOT NULL
                              THEN 1
                          END)
FROM PartData_GKN05_C
WHERE Infeed_Pick_Time >= DATEADD(day, -7, GETDATE());

ALTER TABLE PartData_GKN05_C
ADD Total_Good_Parts INT;

DECLARE @Total_Good_Percent AS FLOAT= ((@Total_Good_Parts / @Total_Parts) * 100.00);