2016-03-02 55 views
6

案例:我在BQ中有Sales表,item_num列包含值1,-1和0.我想統計每個值有多少個案例。在BigQuery中使用IF

在下面嘗試了一個簡單的查詢,但計數返回完全相同的數字爲每個案件..我缺少什麼?

SELECT 
count(if(item_num > 0,1, 0)) as buysplus, 
count(if(item_num < 0,1, 0)) as buysminus, 
count(if(item_num = 0,1, 0)) as buyszero 
from MyShop.Sales 

感謝

回答

8
SELECT 
    SUM(IF(item_num > 0, 1, 0)) AS buysplus, 
    SUM(IF(item_num < 0, 1, 0)) AS buysminus, 
    SUM(IF(item_num = 0, 1, 0)) AS buyszero 
FROM MyShop.Sales 

,甚至它少verbous版本:

SELECT 
    SUM(item_num > 0) AS buysplus, 
    SUM(item_num < 0) AS buysminus, 
    SUM(item_num = 0) AS buyszero 
FROM MyShop.Sales 

這會給喲結果類似下面

buysplus buysminus buyszero  
4   2   3 

另一種辦法是調換版本它是

SELECT 
    item_num AS buys, 
    COUNT(1) AS volume 
FROM MyShop.Sales 
GROUP BY 1 

,結果如下

buys  volume 
0   3  
1   4  
-1   2  
+0

我想補充一點,在BigQuery的標準SQL模式,可以簡化計數(有些人認爲更直觀,如果少便攜式)。可以使用COUNTIF(item_num> 0)來代替SUM(IF(item_num> 0,1,0))' – justbeez