2013-10-23 74 views
1

我有一個表可能在兩列之一列B和/或列C中具有搜索值。我想根據列A產生彙總,顯示所選搜索值(例如x)出現在每個人的任一列中多少次。我想要統計兩列中的總數。Mysql彙總包含兩列中的一列中的值的所有行

+--------+------+----+ 
| name | B | C | 
+--------+------+----+ 
| john | x | z | 
| john | x | x | 
| john | y | x | 
| peter | x | z | 
| peter | x | z | 
| amanda | x | x | 
| amanda | x | x | 
| amanda | x | x | 
| amanda | x | y | 
| amanda | x | y | 
+--------+-----------+ 

在上面的例子中,假設我的搜索值爲x,我要算X出現了多少次的每個人在列B和/或列C.我也想生產總計,併產生這樣的輸出:

Name B C 

john 2 2 
peter 2 0 
amanda 5 3 
total 9 5 

我能做到這一點爲每列分別是這樣的:

 SELECT name, COUNT(*) as count FROM table 
      WHERE A = 'x' 
      GROUP BY name 
      ORDER BY count DESC"; 

    SELECT name, COUNT(*) as count FROM table 
      WHERE B = 'x' 
      GROUP BY name 
      ORDER BY count DESC"; 

然後我就可以從周圍上的每個輸出做單獨取並將它們組合循環,但我想牛逼o知道是否有辦法在兩列的mysql語句中進行檢查和計數?

回答

2

如果你想每一列的總和分別,那麼你可以使用以下(SQL Fiddle):

(
    SELECT MTA.Name, Sum(MTA.B = 'x') AS BSum, Sum(MTA.C = 'x') AS CSum 
    FROM MyTable MTA 
    GROUP BY MTA.Name 
) 
UNION 
(
    SELECT 'Total' AS name, Sum(MTB.B = 'x') AS BSum, Sum(MTB.C = 'x') AS CSum 
    FROM MyTable AS MTB 
) 

或者,如果你想兩者相結合的列然後總和,你可以不喜歡以下(SQL Fiddle):

(
    SELECT MTA.Name, Sum(MTA.B = 'x') + Sum(MTA.C = 'x') AS PersonTotal 
    FROM MyTable MTA 
    GROUP BY MTA.Name 
) 
UNION 
(
    SELECT 'Total' AS name, Sum(MTB.B = 'x') + Sum(MTB.C = 'x') AS PersonTotal 
    FROM MyTable AS MTB 
) 
1
select... 
case count (when A = 'x' then A else null) end, 
case count (when B = 'x' then B else null) end 
... 

編輯: OOP,留出了個性化......

1
SELECT name, 
COUNT(CASE WHEN B='x' THEN 1 ELSE 0 END) as B, 
COUNT(CASE WHEN C='x' THEN 1 ELSE 0 END) as C FROM table 
GROUP BY name; 
1
SELECT name, sum(if(B='x',1,0)) as c1, sum(if(C='x',1,0)) as c2FROM table 
WHERE A = 'x' 
GROUP BY name 
ORDER BY c1 desc, c2 desc 
1

MySQL的快捷方式,

SELECT Name, 
     SUM(B='x') TotalX, 
     SUM(C='x') TotalY 
FROM TableName 
GROUP BY Name 
相關問題