将多行结果合并为一个

时间:2013-02-06 09:26:28

标签: mysql sql group-by pivot

我有一个问题,即将多行结果合并到userID的一行结果中。

我得到了这个结果:

||userID||eventTypeID||COUNT(*)||  
||  1   ||    1      ||    1   ||  
||  1   ||    2      ||    1   ||  
||  2   ||    1      ||    1   ||   
||  3   ||    2      ||    1   ||

我想要的是这样:

||userID||eventTypeID ONE||COUNT()||eventTypeID TWO||COUNT()||

依旧......

我无法弄清楚我是如何做到这一点的,我已经尝试过pivotSQL和concat,但我无法让它工作。

我的SQL查询:

SELECT eventMatch.userID, eventMatch.eventTypeID, COUNT( * )   
FROM  `eventMatch` , activity, activityMatch  
WHERE eventMatch.activityID = activity.activityID  
AND activity.activityID = activityMatch.activityID  
AND activity.khID =1  
GROUP BY eventTypeID, userID  
ORDER BY userID ASC  

希望有人可以提供帮助,也许这很容易,但我已经尝试了2天寻找解决方案: - )

谢谢..

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
  eventMatch.userID, 
  SUM(eventMatch.eventTypeID = 1) As TypeOne,
  SUM(eventMatch.eventTypeID = 2) As TypeTwo, 
  COUNT( * )   
FROM  `eventMatch` 
INNER JOIN activity      ON eventMatch.activityID = activity.activityID 
INNER JOIN activityMatch ON activity.activityID = activityMatch.activityID  
WHERE activity.khID =1  
GROUP BY userID  
ORDER BY userID ASC;

更新1

对于多种事件类型,您可以像这样动态执行此操作:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(em.eventTypeID = ''',
      em.eventTypeID, ''', 1, 0)) AS Type',
      em.eventTypeID )
  ) INTO @sql
FROM  `eventMatch`       AS em;

SET @sql = CONCAT('SELECT em.userID, ', @sql,
                  ', COUNT( * )   
                  FROM  `eventMatch`       AS em
                  INNER JOIN activity      AS  a ON em.activityID = a.activityID 
                  INNER JOIN activityMatch AS am ON a.activityID = am.activityID  
                  GROUP BY em.userID  
                  ORDER BY em.userID ASC  ;');

prepare stmt 
FROM @sql;

execute stmt;

SQL Fiddle Demo


更新2

如果要包含EventTypes表中的所有类型,即使此类型在其他表中没有匹配项,您也应该在此表的第1步中动态获取类型列表{{1而不是从表EventTypes中获取它们,然后以与以前相同的方式执行动态查询。像这样:

eventmatch

Updated SQL Fiddle Demo

答案 1 :(得分:0)

确实

GROUP BY eventMatch.userID, eventMatch.eventTypeID
这份工作?