SQL - 计数和百分比

时间:2011-09-22 14:08:04

标签: sql db2

在单个查询中获得计数和总数的百分比

我想要每个位置的TOTAL单位和所有位置的总百分比......

我得到的是 - 百分比返回0(零) - 我相信我必须将数字转换为十进制或实数类型 - 但无论我尝试(铸造每个元素,或铸造整个结果 - 我得到错误......)

SELECT 
count(I.ID) as count
,L.ID
,(
    count(I.ID) 
    / 
    ( SELECT count(I2.ID) 
      FROM LOCATION L2
      JOIN ITEM I2 ON I2.LocID = L2.ID
      WHERE L2.ID IN (36,38,39,40) )
) AS percent
FROM LOCATION L
JOIN ITEM I ON I.LocID = L.ID
WHERE L.ID IN (36,38,39,40)
GROUP BY L.ID

有关如何返回小数的任何想法??? 或者只是让它更优雅..期间?

我所期待的“

ID      COUNT   PERCENT
2436    362     30.47
2438    184     15.48
2439    173     14.56
2440    172     14.47
2441    151     12.71
2442    54      4.54
2702    92      7.74

====== “t”暗示 - count(I.ID)* 100.0 / count(*)over()AS% 什么是“over()”应该做什么?

这是回报:

ID      COUNT   PERCENT
2436    362     51
2438    184     26
2439    173     24
2440    172     24
2441    151     21
2442    54      7
2702    92      13

==========解决方案

SELECT 
   count(I.ID) as count
   ,L.ID
   ,(
    1.0 * count(I.ID) / (
      SELECT count(I2.ID) 
      FROM LOCATION L2
      JOIN ITEM I2 ON I2.LocID = L2.ID
      WHERE L2.ID = L1.ID )
   ) * 100  AS percent
   FROM LOCATION L
   JOIN ITEM I ON I.LocID = L.ID
WHERE L.ID IN (36,38,39,40)
GROUP BY L.ID

3 个答案:

答案 0 :(得分:1)

简单地乘以浮点/小数值

SELECT 
   count(I.ID) as count
   ,L.ID
   ,(
    100.0 * count(I.ID) 
    / 
     (
      SELECT count(I2.ID) 
      FROM LOCATION L2
      JOIN ITEM I2 ON I2.LocID = L2.ID
      WHERE L2.ID = L1.ID
     )
   ) AS percent
   FROM LOCATION L
   JOIN ITEM I ON I.LocID = L.ID

 WHERE L.ID IN (36,38,39,40)
 GROUP BY L.ID

此外,您需要考虑一个零除数,给出“除以零”错误

答案 1 :(得分:1)

首先,检查您的查询是否有效并返回正确的值:

SELECT 
count(I.ID) as count
,L.ID
,(SELECT count(I2.ID) 
      FROM LOCATION L2
      JOIN ITEM I2 ON I2.LocID = L2.ID
      WHERE L2.ID IN (36,38,39,40)
)
FROM LOCATION L
JOIN ITEM I ON I.LocID = L.ID
WHERE L.ID IN (36,38,39,40)
GROUP BY L.ID

然后使用proper syntax进行DB2转换:

CAST(%Expression% AS data-type)

答案 2 :(得分:0)

您可以使用ROUND()功能......

ROUND(..., 2) AS percent

或者只乘以十进制值(即1.0)。您还可能希望包含IFCASE(取决于您的SQL服务器)以绕过可能的零值