我正在进行查询以计算不同类别的不同类别的条目数。我先按类别对表格的行进行分组,然后按州进行分组。这是我当前查询的一个版本:
SELECT
CASE
WHEN J.MISC_CATEGORY_CONFIG IN (
'A_1',
'A_2'
) THEN 'Category A'
WHEN J.MISC_CATEGORY_CONFIG IN (
'B_1',
'B_2'
) THEN 'Category B'
WHEN J.MISC_CATEGORY_CONFIG IN (
'C_1',
'C_2'
) THEN 'Category C'
ELSE 'Other'/*This should not happen, if it does, something is wrong.*/
END AS CATEGORY,
J.STATUS,
COUNT(*) AS STATUS_COUNT
FROM JOB J
WHERE J.FINISHED_TIME > DATE_SUB(CURDATE(), INTERVAL 7 DAY)
AND (
DAYNAME(J.FINISHED_TIME) = 'Saturday'
OR DAYNAME(J.FINISHED_TIME) = 'Sunday')
AND J.MISC_CATEGORY_CONFIG IN (
/*All relevant categories*/
'A_1',
'A_2',
'B_1',
'B_2',
'C_1',
'C_2'
)
GROUP BY
CASE
WHEN J.MISC_CATEGORY_CONFIG IN (
'A_1',
'A_2'
) THEN 'Category A'
WHEN J.MISC_CATEGORY_CONFIG IN (
'B_1',
'B_2'
) THEN 'Category B'
WHEN J.MISC_CATEGORY_CONFIG IN (
'C_1',
'C_2'
) THEN 'Category C'
ELSE 'Other'/*This should not happen, if it does, something is wrong.*/
END,
J.STATUS
查询结果目前如下所示:
CATEGORY | STATUS | COUNT
Category A Success 117
Category A Failure 19
Category B Success 208
当我需要结果如下:
CATEGORY | STATUS | COUNT
Category A Success 117
Category A Failure 19
Category B Success 208
Category B Failure 0
Category C Success 0
Category C Failure 0
如何修改我的查询以便以这种方式返回空行,这样如果没有行,所有类别都会在结果集中以0显示?
答案 0 :(得分:0)
或许这样的事情:
我们创建了一组包含我们关心的相关类别/状态的数据(我称之为AllCatStat),我们将其加入到作业中的基本数据集中,这样我们就可以分组并获取左侧相关状态记录的计数加入表。这将是0记录到x记录。
SELECT AllCatStat.Category
, AllCatStat.Status
, count(J.Status) as COUNT
/*Get Distinct category and status for all jobs having a misc_Category_Config we care about*/
FROM (SELECT DISTINCT CASE WHEN J.MISC_CATEGORY_CONFIG IN ('A_1','A_2') THEN 'Category A'
WHEN J.MISC_CATEGORY_CONFIG IN ('B_1','B_2') THEN 'Category B'
WHEN J.MISC_CATEGORY_CONFIG IN ('C_1','C_2') THEN 'Category C'
ELSE 'Other' End as Category,
J.Status
FROM JOB
WHERE MISC_CATEGORY_CONFIG IN ('A_1', 'A_2', 'B_1', 'B_2','C_1','C_2')) AllCatStat
/*Get List of Jobs Meeting our criteria and format to desired category*/
LEFT JOIN (SELECT CASE WHEN J.MISC_CATEGORY_CONFIG IN ('A_1','A_2') THEN 'Category A'
WHEN J.MISC_CATEGORY_CONFIG IN ('B_1','B_2') THEN 'Category B'
WHEN J.MISC_CATEGORY_CONFIG IN ('C_1','C_2') THEN 'Category C'
ELSE 'Other' /*This should not happen, if it does, something is wrong.*/
END AS CATEGORY,
J.STATUS
FROM JOB J
WHERE J.FINISHED_TIME > DATE_SUB(CURDATE(), INTERVAL 7 DAY)
AND (DAYNAME(J.FINISHED_TIME) = 'Saturday'
OR DAYNAME(J.FINISHED_TIME) = 'Sunday')
AND J.MISC_CATEGORY_CONFIG IN ('A_1', 'A_2', 'B_1', 'B_2', 'C_1', 'C_2')
) J
ON AllCatStat.Category = J.Category
and AllCatStat.Status = J.Status
GROUP BY AllCatStat.CATEGORY
, AllCatStat.STATUS