SQLite枢轴产生备用NULL

时间:2019-01-16 03:01:23

标签: sqlite pivot

我的SQLite枢纽代码有问题,主要来自McPeppr在这里的答案:Pivot in SQLite

创建临时表:

WITH t1 AS (
SELECT      band, 
    p.name, 
    status, 
    strftime('%Y-%m', time_start) AS Month,
    AVG(time) AS Avg
FROM person p

JOIN action a ON p.person_id = a.person_id
JOIN log l ON p.log_id = l.log_id

WHERE p.person = 'Joe' AND opps = '2'

GROUP BY band, Month, status, strftime('%Y-%m', time_stamp_start)

ORDER BY Month, CASE status
                WHEN 'one' THEN 0
                WHEN 'two' THEN 1
                WHEN 'three' THEN 2
                WHEN 'four' THEN 3
            END
),

t1看起来像:

  band |  name  | status |   month   |     AVG 
 ------+--------+--------+-----------+---------------
    1  |  Joe   |  one   |  2018-01  |     3.33      
    2  |  Joe   |  one   |  2018-01  |     4.11
    1  |  Joe   |  two   |  2018-02  |     2.55      
    2  |  Joe   |  two   |  2018-02  |     3.45 
  ..........     

当我尝试进行选择时,我得到:

Select band, Month,
case when status = 'one' then response_avg end as One,
case when status = 'two' then response_avg end as Two,
...,
from t1

此:

  band |   month    |  One  |  Two  
 ------+------------+-------+---------
    1  |  2018-01   |  3.41 |  NULL    
    2  |  2018-01   |  3.55 |  NULL
    1  |  2018-01   |  NULL |  2.55     
    2  |  2018-01   |  NULL |  4.61
    1  |  2018-02   |  1.55 |  NULL    
    2  |  2018-02   |  2.43 |  NULL
    1  |  2018-02   |  NULL |  4.33     
    2  |  2018-02   |  NULL |  3.44

我要

  band |   month    |  One  |  Two  
 ------+------------+-------+---------
    1  |  2018-01   |  3.41 |  2.55    
    2  |  2018-01   |  3.55 |  4.61
    1  |  2018-02   |  1.55 |  2.55     
    2  |  2018-02   |  2.43 |  4.61

我知道状态列是造成此问题的原因,但无法解决该问题。

我尝试了很多方法,这些方法来自于我在此处发现的不同问题中的多种方法(多个临时表,子选择以删除“状态”(由于默认分组而导致)),但最终得到的结果相同。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

使用CASE / WHEN时的技巧是使用聚合函数(如MAX),然后按所有非聚集列进行分组:

SELECT 
   band,
   Month,
   MAX(CASE 
          when status = 'one' then response_avg
      END) as One,
   MAX(CASE 
          when status = 'two' then response_avg
      END) as Two
FROM t1
GROUP BY band,
   Month