伪列的行上的SQL百分比

时间:2017-03-14 09:26:23

标签: sql-server

我在下面有这个脚本,它显示了我的伪列的百分比。我想介绍另外两列,并获得所有记录的集体数字。

问题是我只得到一个在所有记录上都重复的数字。我做错了什么?

初始脚本

  SELECT ulIDSOrdProductionorTrading
    ,CASE 
        WHEN ulIDSOrdProductionorTrading IN ('Board Split', 'Production - Other')
            THEN 'Production'
        WHEN ulIDSOrdProductionorTrading = 'Trading'
            THEN 'Trading'
        END AS Unit
    ,Score
    ,count(*) * 100.0 / (
        SELECT count(*)
        FROM dbo.Efficiency
        ) AS Percentage
FROM dbo.Efficiency
GROUP BY ulIDSOrdProductionorTrading
    ,Score
添加两列后

    SELECT InvoiceDate
    ,ulIDSOrdProductionorTrading
    ,CASE 
        WHEN ulIDSOrdProductionorTrading IN ('Board Split', 'Production - Other')
            THEN 'Production'
        WHEN ulIDSOrdProductionorTrading = 'Trading'
            THEN 'Trading'
        END AS Unit
    ,Score
    ,COUNT(*) * 100.0 / (
        SELECT COUNT(*) AS Expr1
        FROM dbo.Efficiency
        ) AS Percentage
    ,ucINCInvNumber
    ,ucINCOrderNum
FROM dbo.Efficiency AS Efficiency_1
GROUP BY ulIDSOrdProductionorTrading
    ,Score
    ,InvoiceDate
    ,ucINCInvNumber
    ,ucINCOrderNum

1 个答案:

答案 0 :(得分:0)

您的伪列使用的查询与您的

组无关
ilIDSOrdProductionorTrading, Score, InvoiceDate, ucINCInvNumber, ucINCOrderNum

因为您在该查询中没有wheregroup byhaving combo。您需要在伪列中过滤查询,以确保您对给定组的count具有正确的Efficiency。伪列的唯一变化是外部查询组的count除以常量。