2017-06-19 170 views
0

我正在查看一些關鍵字排名,並且需要帶回關於URL已增加排名的關鍵字數量,排名降低,數據保持不變的數據。我的數據看起來像這樣:如何用mysql執行COUNTIF公式

URL | Keyword | Position | Previous position | Keyword Movement 

example.com/page1 | things to do london | 38 | 101| Up 
example.com/page2 | mens shoes size 8  | 48 | 94 | Up 
example.com/page3 | notebooks    | 22 | 2 | Down 
example.com/page4 | macbook pros for sale | 52 | 52 | Same 
example.com/page1 | homebrew supplies  | 56 | 46 | Down 
example.com/page2 | sql tutorials   | 70 | 39 | Down 
example.com/page3 | random seo keywords | 88 | 36 | Down 
example.com/page4 | best albums of 2017 | 94 | 95 | Up 
example.com/page5 | fender stratocaster | 19 | 9 | Down 
example.com/page6 | qotsa     | 91 | 34 | Down 

我想有一個表格顯示的URL,關鍵字增加數量,沒有。的關鍵字減少,沒有。的關鍵字保持不變。在Excel中,這可以使用countif公式完成,但不知道如何使用mysql來做到這一點。我想要一張如下所示的表格:

URL |Keywords Up |Keywords Down |Keywords remain 


example.com/page1 | 1 | 1 | 0 
example.com/page2 | 1 | 1 | 0 
example.com/page3 | 0 | 2 | 0 
example.com/page4 | 1 | 0 | 1 
example.com/page5 | 0 | 1 | 0 
example.com/page6 | 0 | 1 | 0 

我正在尋找一種在「Movement」列上進行countif的方法。

謝謝。

+0

本質上,你想要做的是創建一個數據透視表。鏈接的重複主題同時描述了靜態(列數已預先知道 - 這可能是您的情況)和動態(列數未知)。但是,請注意,在應用程序邏輯中執行此類轉換可能比在sql代碼中更高效。 – Shadow

回答

1

您可以在Movement列中使用條件聚合,然後計算三種移動類型,按URL分組。

SELECT 
    URL, 
    SUM(CASE WHEN Movement = 'Up' THEN 1 ELSE 0 END) AS keywords_up, 
    SUM(CASE WHEN Movement = 'Down' THEN 1 ELSE 0 END) AS keywords_down, 
    SUM(CASE WHEN Movement = 'Same' THEN 1 ELSE 0 END) AS keywords_remain 
FROM yourTable 
GROUP BY URL