在一个SQL SELECT查询中将百分比添加到多个计数

时间:2009-08-20 13:13:39

标签: sql sql-server sql-server-2005

我有一个类似于下面的SELECT语句,它在一个查询中返回几个计数。

SELECT  invalidCount = (SELECT COUNT(*) FROM <...a...> WHERE <...b...>),
        unknownCount = (SELECT COUNT(*) FROM <...c...> WHERE <...d...>),
        totalCount   = (SELECT COUNT(*) FROM <...e...> WHERE <...f...>)

这很好但我想在SELECT中添加两个百分比列:

invalidCount * 100 / totalCount AS PercentageInvalid, 
unknownCount * 100 / totalCount AS UnknownPercentage

如何修改我的SELECT语句来处理这个问题?

5 个答案:

答案 0 :(得分:4)

您可以在from子句中使用子查询:

select
    s.invalidCount,
    s.unknownCount,
    s.totalCount,
    invalidCount * 100 / s.totalCount as PercentageInvalid,
    unknownCount * 100 / s.totalCount as PercentageUnknown
from
    (select  invalidCount = (SELECT COUNT(*) FROM <...a...> WHERE <...b...>),
        unknownCount = (SELECT COUNT(*) FROM <...c...> WHERE <...d...>),
        totalCount       = (SELECT COUNT(*) FROM <...e...> WHERE <...f...>)) s

答案 1 :(得分:3)

SELECT invalidCount, 
  unknownCount, 
  totalCount, 
  invalidCount * 100 / totalCount AS PercentageInvalid, 
  unknownCount * 100 / totalCount AS UnknownPercentage 
FROM 
    (
      SELECT  invalidCount = (SELECT COUNT(*) FROM <...a...> WHERE <...b...>),  
      unknownCount = (SELECT COUNT(*) FROM <...c...> WHERE <...d...>),     
      totalCount       = (SELECT COUNT(*) FROM <...e...> WHERE <...f...>)
    )

答案 2 :(得分:1)

这是一种使用OVER子句的不同方法,非常酷 - 效率很高。查看针对AdventureWorks的此示例:

SELECT DISTINCT CardType 
        ,COUNT(*) OVER (PARTITION BY CardType) AS TypeCount
        ,COUNT(*) OVER (PARTITION BY 1) AS TotalCount
        ,COUNT(*) OVER (PARTITION BY CardType) / CAST(COUNT(*) OVER (PARTITION BY 1) AS float) AS TypePercent
FROM Sales.CreditCard

答案 3 :(得分:1)

我肯定会选择Mike的解决方案!更优雅,更高效。

但我认为没有理由不在这里使用GROUP BY。这将使它更优雅,更高效。我建议摆脱多余的“COUNT(*)OVER(PARTITION BY 1)”,并将计数加起来。

SELECT CardType 
       , COUNT(*) AS TypeCount
       , SUM(COUNT(*)) OVER () AS TotalCount
       , COUNT(*) * 1.0 / SUM(COUNT(*)) OVER () AS TypePercent
FROM Sales.CreditCard
GROUP BY CardType

注意:

  • “PARTITION BY 1”是多余的,因此省略。
  • 获取CardType-Counts的SUM 我们从整个桌子算一次 再没有分区。
  • * 1.0用于代替铸造。
  • 查询未经过测试,但应该可以正常运行..

答案 4 :(得分:0)

SELECT  invalidCount = (SELECT COUNT(*) FROM <...a...> WHERE <...b...>),
        unknownCount = (SELECT COUNT(*) FROM <...c...> WHERE <...d...>),
        totalCount       = (SELECT COUNT(*) FROM <...e...> WHERE <...f...>)
INTO #tmp

SELECT invalidCount,
       unknownCount,
       totalCount,
       invalidCount * 100 / totalCount AS PercentageInvalid, 
       unknownCount * 100 / totalCount AS UnknownPercentage
FROM #tmp

DROP TABLE #tmp