如何在结果表中添加新列?

时间:2017-07-26 21:18:58

标签: sql hive

这是表mytable

identifier  thedate            direction
111         2017-06-03 11:20   2
111         2017-06-03 12:22   1
222         2017-06-04 12:15   1
333         2017-06-05 12:21   1
444         2017-06-05 12:39   2
444         2017-06-08 14:23   2
555         2017-06-08 15:33   1
555         2017-06-08 16:12   2

我正在计算Apache Hive中唯一标识符的平均每小时数,如下所示:

SELECT HOUR(thedate) as hour, 
       COUNT(DISTINCT identifier, CAST(thedate as date),
       HOUR(thedate)) / COUNT(DISTINCT CAST(thedate as date),
       HOUR(thedate)) as hourly_avg_count
FROM mytable
GROUP BY HOUR(thedate) 

现在我需要将新的计算列添加到结果表(而不是原始列)。名为newcolumn的此列应该对列表Athedate的结果值["2017-06-03","2017-06-04"]。当B属于thedate时,它必须具有值["2017-06-05","2017-06-06"]thedate中未包含在两个列表中的其余值应分配值C

结果表应包含以下列:

newcolumn    hour    hourly_avg_count
A            11      0.5
A            12      1
B            ...     ...            
C            ...     ...

2 个答案:

答案 0 :(得分:2)

您只需将其添加到GROUP BY

即可
SELECT (CASE WHEN DATE(thedate) IN ('2017-06-03', '2017-06-04') THEN 'A'
             WHEN DATE(thedate) IN ('2017-06-05', '2017-06-06') THEN 'B'
             ELSE 'C'
        END) as grp,
       HOUR(thedate) as hour, 
       COUNT(DISTINCT identifier, CAST(thedate as date), HOUR(thedate)
             ) / COUNT(DISTINCT CAST(thedate as date), HOUR(thedate)) as hourly_avg_count
FROM mytable
GROUP BY HOUR(thedate),
         (CASE WHEN DATE(thedate) IN ('2017-06-03', '2017-06-04') THEN 'A'
               WHEN DATE(thedate) IN ('2017-06-05', '2017-06-06') THEN 'B'
               ELSE 'C'
          END);

答案 1 :(得分:0)

使用案例陈述

SELECT CASE WHEN thedate BETWEEN '2017-06-03' AND '2017-06-04'
            THEN 'A'
            WHEN thedate BETWEEN '2017-06-05' AND '2017-06-06'
            THEN 'B'
            ELSE 'C'
        END newcolumn

...