2014-05-08 32 views
1

我有以下格式组按日期和获取特定领域的计数

'-------------------------------------- 
    ID|col1 |date_ts 
-------------------------------------- 
1 |type1 | 2011-10-01 23:59:59.163-08 
2 |type1 | 2011-10-02 21:42:20.152-19 
3 |type2 | 2011-10-03 23:21:49.175-21 
4 |type3 | 2011-10-03 23:19:39.169-12 
5 |type2 | 2011-10-05 23:34:30.129-01' 

我想按日期,并得到每种类型的计数COL1

下表是输出I我试图实现

' date  | type1 | type2  |type3 | 
------------------------------------------ 
2011-10-01 | 1 | 0  | 0 | 
2011-10-02 | 1 | 0  | 0 | 
2011-10-03 | 0 | 1  | 1 | 
2011-10-05 | 0 | 1  | 0 |' 

我现在有下面的查询。但获取运行时错误。

'set hive.cli.print.header=true; 
select 
sum(if(col1 = 'type1', 1, 0)) as type_1, 
sum(if(col1 = 'type2', 1, 0)) as type_2, 
sum(if(col1 = 'type3', 1, 0)) as type_3 
from table1 WHERE unix_timestamp(date_ts) >= unix_timestamp('2011-10-01 00:00:00.178-01') AND  unix_timestamp (date_ts) <= unix_timestamp('2011-10-05 23:59:59.168-08') 
GROUP BY col1, TO_DATE(date_ts) 
ORDER BY date_ts;' 

如何做到这一点的任何想法?谢谢

+0

什么语言,你会被将其应用到? –

+0

我正在尝试在蜂巢中执行 – dheee

+0

您遇到的错误是什么? –

回答

1

您需要在投影列暴露date_ts。

选择TO_DATE(date_ts)date_ts, SUM(IF(COL1 = 'TYPE1',1,0))作为TYPE_1, SUM(IF(COL1 = '2型',1,0))作为TYPE_2 , SUM(IF(COL1 = 'TYPE3',1,0))作为TYPE_3 从表1 WHERE UNIX_TIMESTAMP(date_ts)> = UNIX_TIMESTAMP( '2011-10-01 00:00:00.178-01')AND UNIX_TIMESTAMP(date_ts )< = UNIX_TIMESTAMP( '2011-10-05 23:59:59.168-08') GROUP BY COL1,TO_DATE(date_ts) ORDER BY date_ts;”

+0

对不起,它不工作。我认为你提到的查询可能是正确的,但是我的数据在date_ts列中有一些异常。因此,使用数据类型字符串而不是时间戳,并使用子字符串来获取所需的输出。 – dheee

+0

那么我指出了方向:你自己的解决方案确实包含了在所选列中包含date_ts列的方面。这是你是否选择奖励给我,但在相反的情况下,我只有在没有其他答案对他有帮助时才奖励自己。 – javadba

+0

thx!我也赞成你的解决方案,以表彰你的工作。 – javadba

1

我删除了where条件筛选出的日期。我用一个子串来获取整个列的日期部分。而只是做了GROUP BY仅日期列

'select substr(ltrim(date_ts),0,10) date_ts, 
sum(if(col1 = 'type1', 1, 0)) as type_1, 
sum(if(col1 = 'type2', 1, 0)) as type_2, 
sum(if(col1 = 'type3', 1, 0)) as type_3 
from table1 
GROUP BY substr(ltrim(date_ts),0,10) 
ORDER BY date_ts;' 

我的输出

' date  | type1 | type2  |type3 | 
------------------------------------------ 
2011-10-01 | 1 | 0  | 0 | 
2011-10-02 | 1 | 0  | 0 | 
2011-10-03 | 0 | 1  | 1 | 
2011-10-05 | 0 | 1  | 0 |'