如何在sqlite计算字段中返回十进制数

时间:2015-10-18 01:59:10

标签: sql sqlite

我有以下查询:

SELECT
    qryFoodInCases.fldCaseID,
    qryFoodInCases.fldFood,
    AteAttackRate,
    NotAteAttackRate,
    Round( AteAttackRate / NotAteAttackRate, 2 ) RelativeRisk
FROM
    qryFoodInCases
    LEFT JOIN
    (
        SELECT
            qryNotAteInCase.fldCaseID,
            qryNotAteInCase.fldFood,
            COALESCE( qryNotAteAndGotSick.NotAteAndGotSick, 0 ) NotAteAndGotSick,
            qryNotAteInCase.NotAteInCase
            TotalNotAte,
            100 * COALESCE( qryNotAteAndGotSick.NotAteAndGotSick, 0 ) / qryNotAteInCase.NotAteInCase NotAteAttackRate
        FROM
            qryNotAteInCase
            LEFT JOIN qryNotAteAndGotSick ON qryNotAteInCase.fldFood = qryNotAteAndGotSick.fldFood
        GROUP  BY qryNotAteInCase.fldFood
    ) QA
        ON qryFoodInCases.fldFood = QA.fldFood

    LEFT JOIN
    (
        SELECT
            qryFoodInCases.fldCaseID,
            qryFoodInCases.fldFood,
            COALESCE( qryAteAndGotSick.AteAndGotSick, 0) AteAndGotSick,
            qryFoodInCases.fldFoodFrequency TotalAte,
            100 * COALESCE( qryAteAndGotSick.AteAndGotSick, 0 ) / qryFoodInCases.fldFoodFrequency AteAttackRate
        FROM
            qryFoodInCases
            LEFT JOIN qryAteAndGotSick ON qryFoodInCases.fldFood = qryAteAndGotSick.fldFood
        GROUP BY
            qryFoodInCases.fldFood
    ) QN
        ON qryFoodInCases.fldFood = QN.fldFood

GROUP BY
    qryFoodInCases.fldFood
ORDER BY
    AteAttackRate DESC,
    NotAteAttackRate 

注意:只有select语句的最后一个字段与此问题相关:

 round(AteAttackRate/NotAteAttackRate,2) RelativeRisk

返回以下记录

+-----------+------------+---------------+------------------+--------------+
| fldCaseID |  fldFood   | AteAttackRate | NotAteAttackRate | RelativeRisk |
+-----------+------------+---------------+------------------+--------------+
|         1 | Beans      |           100 |               33 |            3 |
|         1 | Cabagge    |            66 |               75 |            0 |
|         1 | fried fish |            66 |               75 |            0 |
|         1 | Banana     |            50 |               80 |            0 |
|         1 | Pork       |            50 |              100 |            0 |
|         1 | Chicken    |            33 |              100 |            0 |
|         1 | Potatoes   |             0 |              100 |            0 |
|         1 | Rice       |             0 |              100 |            0 |
+-----------+------------+---------------+------------------+--------------+

如何获取字段RelativeRisk

的十进制值,我需要做什么

1 个答案:

答案 0 :(得分:4)

尝试:

select 
    ... 
    round(AteAttackRate/cast(NotAteAttackRate as float),2) RelativeRisk
    ... 

AteAttackRateNotAteAttackRate都是整数,因此AteAttackRate / NotAteAttackRate也是整数,round(AteAttackRate / NotAteAttackRate, 2)不会改变任何内容。您必须显式转换为浮动至少一个数字才能获得浮点商。