0

可能重复:
MySQL 将行转换为动态列数

我有一个查询显示每天的项目数

$query = "SELECT uploadedby, count(item) as item, date_format(uploaddate, '%m-%d-%y') as date FROM `imsexport` GROUP BY uploadedby,date";
$result = mysql_query($query);

结果表如下所示

   Name        item    date
Abel Antonio    10   01-02-12
Abel Antonio    5    01-03-12
Abel Antonio    6    01-04-12
Abel Antonio    2    01-05-12
Abel Antonio    1    01-09-12
Abel Antonio    15   01-12-12
Abel Antonio    22   01-16-12
Abel Antonio    15   01-17-12
Abel Antonio    7    01-19-12
Abel Antonio    45   02-15-12
Abel Antonio    31   02-16-12
...other names

我想将日期作为列以使查询看起来像这样

Name          01-02-12  01-03-12   01-04-12   01-05-12    01-09-12 ....
Abel Antonio    10         5          6          2           1     .....

有谁知道如何做到这一点?

4

2 回答 2

0

所以我认为你想使用动态列数来做一个 Pivot。这取决于您使用的数据库,但我通过 date_format 语句猜测它是 MYSQL。这是一个答案的链接,可以满足您的要求 - 享受吧!

https://stackoverflow.com/a/12005676/345659

您的代码应如下所示:

$query = "
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT('count(case when date_format(uploaddate, ''%m-%d-%y'') = ''',
      date_format(uploaddate, '%m-%d-%y'),
      ''' then 1 end) AS `',
      date_format(uploaddate, '%m-%d-%y'), '`'
    )
  ) INTO @sql
from imsexport;

SET @sql = CONCAT('SELECT uploadedby AS Name, ', 
                  @sql, 
                  ' FROM imsexport 
                    GROUP BY Name');

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

$result = mysql_query($query);

我在链接问题中由 bluefeet 提供的小提琴中使用了这些数据:

create table imsexport
(
  uniqueID int,
  item varchar(10),
  uploadedby varchar(50),
  uploaddate datetime
);
insert into imsexport values (1, 'Product A', 'Abel Antonio', '2013-01-01');
insert into imsexport values (2, 'Product B', 'Abel Antonio', '2013-01-01');
insert into imsexport values (3, 'Product C', 'Abel Antonio', '2013-01-01');
insert into imsexport values (4, 'Product A', 'Abel Antonio', '2013-01-01');
insert into imsexport values (5, 'Product A', 'Abel Antonio', '2012-01-01');
insert into imsexport values (6, 'Product A', 'Abel Antonio', '2012-01-01');
insert into imsexport values (7, 'Product A', 'Abel Antonio', '2012-01-01');
于 2013-01-09T06:14:19.390 回答
0

在应用程序级别处理显示逻辑。

于 2013-01-09T07:49:57.820 回答