以下是我的表格的样子:
VIDEO_ID DATETIME APPROVED VIOLATION_COUNT VIDEO_DESCRIPTION
VIDEO1 2018-01-02 yes 1 a
VIDEO2 2018-06-02 no 2 b
VIDEO3 2018-07-04 yes 1 c
VIDEO4 2018-01-12 yes 1 b
VIDEO5 2018-06-02 no 2 c
VIDEO6 2018-07-29 yes 1 a
我需要通过VIDEO_TYPE对此表进行分组(我由VIDEO_DESCRIPTION确定,这就是为什么我使用SWITCH-CASE语句,请参阅下面的查询)。 然后,对于每个VIDEO_TYPE,我需要计算两件事:
所以我希望我的查询返回3列: VIDEO_TYPE ,总计 VIOLATION_COUNT 的总和以及 VIOLATION_COUNT的总和,其中APPROVED ='是&#39 ; ,每个 VIDEO_TYPE 。
我的问题是如何计算VIOLATION_COUNT的总和以及VIOLATION_COUNT的总和,其中APPROVED =" yes" 在同一时间?
这是我的问题:
SELECT
CASE
WHEN VIDEO_DESCRIPTION = 'a' THEN 'Video type 1'
WHEN VIDEO_DESCRIPTION = 'b' THEN 'Video type 2'
WHEN VIDEO_DESCRIPTION = 'c' THEN 'Video type 3'
ELSE 'Others' END AS VIDEO_TYPE,
SUM(VIOLATION_COUNT) AS VIOLATION_COUNT,
(select count(APPROVED) where APPROVED = 'yes') AS TRUE_POSITIVE_VIOL_COUNT, -- THIS IS NOT WORKING
FROM my_table
GROUP BY
VIDEO_TYPE
此查询给出了此错误:
无效操作:子查询使用未分组的列" my_table.approved" 来自外部查询;
答案 0 :(得分:1)
您可以添加SUM(CASE)来解决此问题:
SELECT CASE WHEN VIDEO_DESCRIPTION = 'a' THEN 'Video type 1'
WHEN VIDEO_DESCRIPTION = 'b' THEN 'Video type 2'
WHEN VIDEO_DESCRIPTION = 'c' THEN 'Video type 3'
ELSE 'Others' END AS VIDEO_TYPE,
SUM(VIOLATION_COUNT) AS VIOLATION_COUNT,
SUM(CASE WHEN APPROVED = 'yes' THEN 1 ELSE 0 END) AS TRUE_POSITIVE_VIOL_COUNT
FROM tbl
GROUP BY VIDEO_DESCRIPTION;
VIDEO_TYPE | VIOLATION_COUNT | TRUE_POSITIVE_VIOL_COUNT :----------- | --------------: | -----------------------: Video type 1 | 2 | 2 Video type 2 | 3 | 1 Video type 3 | 3 | 1
db<>小提琴here