2013-08-28 103 views
0

Iam new in stackoverflow,我有一些問題試圖做主題。報告。Mysql交叉表驗證是否存在

表範例

 
Group Client Atribute 
Group1 Client1 Atribute1 
Group1 Client1 Atribute1 
Group1 Client2 Atribute2 
Group2 Client3 Atribute1 
Group3 Client4 Atribute2 
Group3 Client5 Atribute2 
Group3 Client5 Atribute2 
Group3 Client6 Atribute3 

注意:客戶端和組列將repetead如這個例子。

所需報告

 
Group Client Atribute1 Atribute2 Atribute3 
Group1 Client1 Yes   no  no 
Group1 Client2 no   yes  no 
Group2 Client3 yes   no  no 
Group3 Client4 no   yes  no 
Group3 Client5 no   yes  no 
Group3 Client6 no   no  yes 

主要併發症是,我們需要通過客戶驗證客戶是否哈弗還是不具有diferent atributes。

我被困在一開始,我以爲是這樣的:

SELECT 
group, 
client, 
CASE WHEN EXISTS 
(SELECT client FROM table 
    WHERE client IN (SELECT client FROM table 
    WHERE Atribute = 3) -- The problem is that since there is an attribute for one of the clients the subquery result true and will go to the "THEN" dor all the clients. 
) THEN 'Yes' ELSE 'No' END AS Atribute3, 
FROM 
table 
GROUP BY group, client 

任何幫助將不勝感激。請原諒我的英語!最好的reggards。

回答

0

您可以使用動態SQL做這樣的

SET @sql = NULL; 

SELECT GROUP_CONCAT(DISTINCT 
     CONCAT('MAX(CASE WHEN atribute = ''', 
       atribute, 
       ''' THEN ''yes'' ELSE ''no'' END) ', 
       atribute)) 
    INTO @sql 
    FROM table1; 

SET @sql = CONCAT('SELECT `group`, client, ', @sql, ' 
        FROM table1 
        GROUP BY `group`, client'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

輸出:

 
| GROUP | CLIENT | ATRIBUTE1 | ATRIBUTE2 | ATRIBUTE3 | 
|--------|---------|-----------|-----------|-----------| 
| Group1 | Client1 |  yes |  no |  no | 
| Group1 | Client2 |  no |  yes |  no | 
| Group2 | Client3 |  yes |  no |  no | 
| Group3 | Client4 |  no |  yes |  no | 
| Group3 | Client5 |  no |  yes |  no | 
| Group3 | Client6 |  no |  no |  yes | 

這裏是SQLFiddle演示

要在主叫端簡化的東西,你可以把它包裝進入存儲過程

DELIMITER $$ 
CREATE PROCEDURE sp_report() 
BEGIN 
    SET @sql = NULL; 

    SELECT GROUP_CONCAT(DISTINCT 
      CONCAT('MAX(CASE WHEN atribute = ''', 
        atribute, 
        ''' THEN ''yes'' ELSE ''no'' END) ', 
        atribute)) 
    INTO @sql 
    FROM table1; 

    SET @sql = CONCAT('SELECT `group`, client, ', @sql, ' 
        FROM table1 
        GROUP BY `group`, client'); 

    PREPARE stmt FROM @sql; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt; 
END$$ 
DELIMITER ; 

,然後用它像

CALL sp_report(); 

這裏是SQLFiddle演示