2010-11-16 66 views
1

嗨,似乎不能構建後MYSQL查詢我。在查詢中使用MYSQL條件語句和變量

說我有兩欄的結果:1)瀏覽器名稱和2)瀏覽器計數。

其中變得複雜的是我希望一旦達到總數的90%,就可以將所有其他瀏覽器重命名爲其他瀏覽器,並相應地標記剩餘百分比。

我知道我能得到總數爲變量我開始主語句之前:

SELECT @total := COUNT(id) FROM browser_table WHERE start LIKE "2010%"; 

然後我就可以組的結果通過瀏覽器:

SELECT browser, COUNT(id) AS visits 
FROM browser_table 
WHERE start LIKE "2010%" 
GROUP BY browser 

我知道我需要在一個case語句(和一個計數器變量)中敲擊來對列進行排序,但不知道如何執行到上述查詢中:

CASE 
    WHEN counter >= 0.9* @total THEN 'other' 
    ELSE browser 
END AS browser; 

希望有道理?感謝您的時間....

回答

0

這裏有一個辦法......

可以計算基於this answer總運行。例如:

SET @rt := 0; 
SELECT 
    browser, 
    visits, 
    (@rt := @rt + visits) AS running_total 
FROM 
    (
     SELECT 
      browser, 
      COUNT(id) AS visits 
     FROM 
      browser_table 
     WHERE 
      start LIKE '2010%' 
     GROUP BY 
      browser 
     ORDER BY 
      visits DESC 
    ) AS sq 
; 


一旦你有了到位,您可以以此爲基礎創建一個「其他」類別:

SET @threshold := (SELECT COUNT(id) FROM browser_table WHERE start LIKE '2010%') * 0.90; 
SET @rt := 0; 
SELECT 
    browser, 
    SUM(visits) AS total_visits 
FROM 
    (
     SELECT 
      IF (@rt < @threshold, browser, 'Other') AS browser, 
      visits, 
      (@rt := @rt + visits) AS running_total 
     FROM 
      (
       SELECT 
        browser, 
        COUNT(id) AS visits 
       FROM 
        browser_table 
       WHERE 
        start LIKE '2010%' 
       GROUP BY 
        browser 
      ) AS sq1 
     ORDER BY 
      visits DESC 
    ) AS sq2 
GROUP BY 
    browser 
ORDER BY 
    total_visits DESC 
;