SQLITE如何在同一查询中划分两个计数结果

时间:2015-08-04 11:00:55

标签: sql sqlite

我目前的代码:

SELECT VENDOR.[VENDOR_NAME], DEVICE.[DEVICE_NAME], DEVICE.[PK_DEVICE],MODELDEVICE.[FK_MODELDEVICE_DEVICE],

COUNT(RESULT.[FK_RESULT_COMMAND]) AS TOTAL_TESTS,
COUNT(case when TYPERESULT.[TYPERESULT_NAME]='ERROR' then 1 else null end) as ERROR,
COUNT(case when TYPERESULT.[TYPERESULT_NAME]='OK' then 1 else null end) as OK,
COUNT(case when TYPERESULT.[TYPERESULT_NAME]='SKIP' then 1 else null end) as SKIP,
COUNT(DISTINCT PK_COMMAND) AS COMMAND_COUNT, 
COUNT(DISTINCT RESULT_ORDER) AS RESULT_COUNT

问题是我需要另一个专栏,结果是将总ERROR结果除以TOTAL_TESTS结果,我不知道该怎么做

2 个答案:

答案 0 :(得分:2)

在这种情况下,我倾向于使用SUM(),而不是COUNT()。我想你会明白为什么,因为平均值也很容易计算:

    COUNT(*) AS TOTAL_TESTS,
    SUM(case when TYPERESULT.[TYPERESULT_NAME] = 'ERROR' then 1 else 0 end) as ERROR,
    SUM(case when TYPERESULT.[TYPERESULT_NAME] = 'OK' then 1 else 0 end) as OK,
    AVG(case when TYPERESULT.[TYPERESULT_NAME] = 'ERROR' then 1.0 else 0 end) as ERROR,
    . . .

请注意1.0的使用。这是因为SQLite执行整数除法,因此我们需要传入一个非整数值。

答案 1 :(得分:1)

只划分2列。

SELECT VENDOR.[VENDOR_NAME], DEVICE.[DEVICE_NAME], DEVICE.[PK_DEVICE],MODELDEVICE.[FK_MODELDEVICE_DEVICE],
COUNT(RESULT.[FK_RESULT_COMMAND]) AS TOTAL_TESTS,
COUNT(CASE WHEN TYPERESULT.[TYPERESULT_NAME] = 'ERROR' THEN 1 ELSE NULL END) AS ERROR,
COUNT(CASE WHEN TYPERESULT.[TYPERESULT_NAME] = 'OK' THEN 1 ELSE NULL END) AS OK,
COUNT(CASE WHEN TYPERESULT.[TYPERESULT_NAME] = 'SKIP' THEN 1 ELSE NULL END) AS SKIP,
COUNT(DISTINCT PK_COMMAND) AS COMMAND_COUNT, 
COUNT(DISTINCT RESULT_ORDER) AS RESULT_COUNT,
(COUNT(CASE WHEN TYPERESULT.[TYPERESULT_NAME] = 'ERROR' THEN 1.0 ELSE NULL END))/(COUNT(RESULT.[FK_RESULT_COMMAND])) AS DivColumn