如何在 DB2 中找到 table 中记录的百分比?

How can I find the percentage of records in a table in DB2?

我有一个 table - drivers 我想知道与所有活跃的 driver 相比,本月终止的 driver 的百分比是多少。我想我已经让它变得非常复杂,虽然它确实 return 结果它只是一个 0。我尝试使用 cast 作为十进制但这对我来说不起作用,因为计算结果仍然是 0.

WITH X AS
( 
SELECT
CAST(COUNT(*) AS DECIMAL (5,2)) TERMINATED,
0 ACTIVE
FROM DRIVER WHERE 
MONTH(TERMINATION_DATE) = MONTH(CURRENT TIMESTAMP) AND YEAR(TERMINATION_DATE) = YEAR(CURRENT TIMESTAMP)

UNION ALL

SELECT 
0 TERMINATED,
CAST(COUNT(*) AS FLOAT) ACTIVE
FROM DRIVER WHERE
ACTIVE_IN_DISP = 'True'
)

SELECT
CAST(SUM(TERMINATED)/(SUM(ACTIVE) + SUM(TERMINATED)*100) AS DECIMAL (10,2))
FROM X

你的括号有点偏离,而不是

SUM(TERMINATED)/(SUM(ACTIVE) + SUM(TERMINATED)*100)
它应该是

SUM(TERMINATED)/(SUM(ACTIVE) + SUM(TERMINATED))*100

你的数字太小,这就是为什么它不适合小数点后两位。

我会这样重写您的查询:

WITH begin_of_month(begin_of_month) AS (VALUES CURRENT DATE - (DAY(CURRENT DATE)-1) DAYS),
X AS (
  SELECT COUNT(*) AS terminated, 0 AS active
    FROM driver
    WHERE termination_date >= begin_of_month
      AND termination_date <  begin_of_month + 1 MONTH --index, if present, can be used!
  UNION ALL
  SELECT 0 AS terminated, COUNT(*) AS active
    FROM driver
    WHERE active_in_disp = 'True'
)
SELECT CAST(FLOAT(SUM(TERMINATED))/(SUM(ACTIVE) + SUM(TERMINATED))*100 AS DECIMAL (10,2)) --CAST only if You wish to display with 2 decimal places
  FROM X