我的数据库中有以下表格
我需要一个选择查询才能获得:
所以我的结果是这样的:
类型2计数类型2 AVG(持续时间)类型1 AVG(持续时间)类型2
1029 20 15 200 156
获得上述结果的确切查询是什么?
答案 0 :(得分:1)
这就是你在找什么:
SELECT DISTINCT a,
SUM(CASE WHEN type = 1 THEN 1 ELSE 0 END) OVER (PARTITION BY a) AS count_of_type_1,
SUM(CASE WHEN type = 2 THEN 1 ELSE 0 END) OVER (PARTITION BY a) AS count_of_type_2,
SUM(CASE WHEN type = 3 THEN 1 ELSE 0 END) OVER (PARTITION BY a) AS count_of_type_3,
AVG(CASE WHEN type = 1 THEN duratuion ELSE 0 END) OVER (PARTITION BY a) AS avg_duration_of_type_1,
AVG(CASE WHEN type = 2 THEN duratuion ELSE 0 END) OVER (PARTITION BY a) AS avg_duration_of_type_2,
AVG(CASE WHEN type = 3 THEN duratuion ELSE 0 END) OVER (PARTITION BY a) AS avg_duration_of_type_3,
SUM(CASE WHEN type = 1 THEN duratuion ELSE 0 END) OVER (PARTITION BY a) AS total_duration_of_type_1,
SUM(CASE WHEN type = 2 THEN duratuion ELSE 0 END) OVER (PARTITION BY a) AS total_duration_of_type_2,
SUM(CASE WHEN type = 3 THEN duratuion ELSE 0 END) OVER (PARTITION BY a) AS total_duration_of_type_3
FROM your_table