2

我有一个与此类似的数据库(MySQL 5.5):

ID    Name   Page Visited   Date
1     Tim     Page A         11-2-2000
1     Tim     Page B         11-3-2000
1     Tim     Page B         11-3-2000
2     Jeff    Page C         11-5-2000
2     Jeff    Page A         11-11-2000

我想构建一个查询(目前正在尝试),结果将类似于:

ID    Name    Page A Visits  Page B Visits  Page C Visits
1     Tim          1             2               0

我假设我需要对一个子集运行以下查询(我的问题是如何使用基本上 3 个计数来执行此操作)?:

SELECT * From database.mytable GROUP BY ID HAVING COUNT(*) >=1
4

1 回答 1

6
SELECT ID, Name,
        SUM(CASE WHEN `Page Visited` = 'Page A' THEN 1 ELSE 0 END) `Page A Visit`,
        SUM(CASE WHEN `Page Visited` = 'Page B' THEN 1 ELSE 0 END) `Page B Visit`,
        SUM(CASE WHEN `Page Visited` = 'Page C' THEN 1 ELSE 0 END) `Page C Visit`
FROM tableName
GROUP BY ID, Name

如果您的数量不详page,您也可以PreparedStatement

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN `Page Visited` =''',
      `Page Visited`,
      ''' then 1 ELSE 0 end) AS ',
      CONCAT('`',`Page Visited`, ' Visits`')
    )
  ) INTO @sql
FROM TableName;

SET @sql = CONCAT('SELECT ID, Name, ', @sql, ' 
                   FROM tableName
                   GROUP BY ID, Name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2012-11-19T03:48:38.720 回答