2012-01-19 60 views
3

我試圖做多個計數在同一列與不同的地方像子句。多個計數在同一列與哪裏像 - MySQL

我已經找出了每個類似子句的基本查詢,但我需要將它們組合起來以產生一個結果。

select system_user, COUNT(details) from asset_log where details like 'Viewed'; 
select system_user, COUNT(details) from asset_log where details like 'Viewed Web%'; 
select system_user, COUNT(details) from asset_log where details like 'ThumbView'; 
select system_user, COUNT(details) from asset_log where details like 'Exported%'; 

我相信它是可能的,我只是不知道該怎麼做。任何幫助,將不勝感激。

在此先感謝

更新:

就這樣結束了,我的工作

select distinct system_user, 
    SUM(CASE WHEN details ='viewed' then 1 Else 0 end) AS viewed_count, 
    SUM(CASE WHEN details Like 'Viewed Web%' then 1 Else 0 end) AS Web_count, 
    SUM(CASE WHEN details = 'ThumbView' then 1 Else 0 end) AS ThumbView_count, 
    SUM(CASE WHEN details Like 'Exported%' then 1 Else 0 end) AS Exported_count 
from asset_log GROUP BY system_user; 

謝謝!

回答

5

你可以用SUM /案例爲「支點」的計數

select system_user, 

    SUM(CASE WHEN details ='viewed' then 1 Else 0 end) viewed_count 
    SUM(CASE WHEN details Like 'Viewed Web%' then 1 Else 0 end) Viewed Web_count 
    SUM(CASE WHEN details = 'ThumbView' then 1 Else 0 end) ThumbView_count 
    SUM(CASE WHEN details Like 'Exported%' then 1 Else 0 end) Exported_count 
from asset_log 
where 
    details = 'viewed' or 
    details like 'Viewed Web%' or 
    details = 'ThumbView' or 
    details like 'Exported%' 
group by 
     system_user 

注:我不會刻意去用「像「沒有通配符

+0

有趣的是,它只產生一個用戶名? – rreeves

+0

哎喲忘了羣 –

1

您可以使用SUM/CASE的組合來實現所需的結果,例如在答案https://stackoverflow.com/a/8870028/625594中。

對於您的情況下,準確的查詢將是:

select system_user, 
SUM(CASE WHEN details like 'Viewed' THEN 1 ELSE 0) AS `sum1`, 
SUM(CASE WHEN details like 'Viewed Web%' THEN 1 ELSE 0) AS `sum2`, 
SUM(CASE WHEN details like 'ThumbView' THEN 1 ELSE 0) AS `sum3`, 
SUM(CASE WHEN details like 'Exported%' THEN 1 ELSE 0) AS `sum4` 
from asset_log; 
1

你可以寫這樣的:

SELECT MAX(system_user) AS system_user, COUNT(*) 
    FROM asset_log 
    WHERE details = 'Viewed' 
    OR details like 'Viewed Web%' 
    OR details = 'ThumbView' 
    OR details like 'Exported%' 

由於system_user大概都是一樣的,所以MAX()只會隨機得到一個,它可以解決不能將聚合列與非聚合列組合的問題。