3

我在按用户 ID 将多行结果组合成一行结果时遇到问题。

我得到这个结果:

||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 天了:-)

谢谢..

4

2 回答 2

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 小提琴演示


更新 2

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

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(em.eventTypeID = ''',
      em.eventTypeID, ''', 1, 0)) AS Type',
      em.eventTypeID )
  ) INTO @sql
FROM  eventTypes       AS em; -- <---------- this is what I changed.


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 演示

于 2013-02-06T09:29:36.720 回答
0

GROUP BY eventMatch.userID, eventMatch.eventTypeID

工作?

于 2013-02-06T09:29:54.960 回答