0

嗨,我有一张看起来像这样的桌子

dt   ticker  open
1     A        1
1     B        3
2     A        1.1
2     B        2.5

我需要结果看起来像

dt    A        B
1     1        3
2     1.1      2.5

我在下面包含的当前查询让我

dt    A        B
1     1        NULL
1     NULL     3
2     1.1      NULL
2     NULL     2.5

如果有人可以帮助我,将不胜感激

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      '(IF(ticker = ''',
      ticker,
      ''', open, NULL)) AS ''',
      ticker,''''
    )
  ) INTO @sql
FROM
  prices;

SET @sql = CONCAT('SELECT dt, ', @sql, ' FROM prices');
-- SET @sql = CONCAT('SELECT dt, ', @sql, ' FROM prices GROUP BY dt');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
4

4 回答 4

1

获得结果的一种方法是:

SELECT t.dt
     , MAX(IF(t.ticker='A',t.open,NULL)) AS A
     , MAX(IF(t.ticker='B',t.open,NULL)) AS B
  FROM mytable t
 GROUP BY t.dt

(在 MySQL 中,MAX 聚合实际上可以省略,认为在其他 DBMS 中需要聚合。)

SELECT t.dt
     , IF(t.ticker='A',t.open,NULL) AS A
     , IF(t.ticker='B',t.open,NULL) AS B
  FROM mytable t
 GROUP BY t.dt

另一种方法:

SELECT t.dt
     , t.open AS A
  FROM mytable t
  LEFT
  JOIN (SELECT s.dt
             , t.open AS B
          FROM mytable s
         WHERE s.ticker = 'B'
         GROUP BY s.dt
       ) b
    ON b.dt = t.dt
 WHERE t.ticker = 'A'
 GROUP BY t.dt
 ORDER BY t.dt
于 2013-01-19T06:20:42.977 回答
0

您需要将 Max 添加到您的 Group_Concat,试试这个

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'Max(case when ticker = ''',
      ticker,
      ''' then open end) AS ',
      replace(ticker, ' ', '')
    )
  ) INTO @sql
from prices;

SET @sql = CONCAT('SELECT x.dt, ', @sql, ' from prices x
group by x.dt');

PREPARE stmt FROM @sql;
EXECUTE stmt;

SQL 小提琴演示

于 2013-01-19T05:56:35.920 回答
0

尝试这个:

SELECT GROUP_CONCAT(CONCAT(" MAX(IF(ticker = '", ticker, "', open, NULL)) AS ", ticker)) INTO @sql
FROM prices;

SET @sql = CONCAT('SELECT dt, ', @sql, ' FROM prices GROUP BY dt'); 

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

检查这个SQL FIDDLE 演示

输出

| DT |   A |   B |
------------------
|  1 |   1 |   3 |
|  2 | 1.1 | 2.5 |
于 2013-01-19T06:02:16.447 回答
0

试试看

    select a.dt,a.A,CASE WHEN ticker='B' THEN open END AS 'B' from (SELECT dt,CASE WHEN ticker='A' THEN open END AS 'A' FROM test group by dt) a inner join test using(dt) where CASE WHEN ticker='B' THEN open END  is not null;

结果

+------+-------------------+------+
| dt   | A                 | B    |
+------+-------------------+------+
|    1 |                 1 |    3 |
|    2 | 1.100000023841858 |  2.5 |
+------+-------------------+------+
于 2013-01-19T06:10:16.000 回答