特定的SQL查询AVG和计数

时间:2015-12-09 10:12:20

标签: sql sql-server

我的数据库中有以下表格

My Table

我需要一个选择查询才能获得:

  1. 每个A的总持续时间,其中Type = 1 ... type = 2 ... type = 3
  2. 每种类型的计数(A)(其中type-1 ... type = 2且type = 3
  3. 所以我的结果是这样的:

    类型2计数类型2 AVG(持续时间)类型1 AVG(持续时间)类型2

    1029 20 15 200 156

    获得上述结果的确切查询是什么?

1 个答案:

答案 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