1

我在 phpMyAdmin 中使用 MySQL,我有一个表,我试图从中获得以下结果,如下图所示:

我有一个表 Rate 结构如下;

+---------+-----------+-------+--------+---------+----------+
| EntryID | RegDate   |  Code | Buying | Selling | Averages |
+---------+-----------+-------+--------+---------+----------+
| 1       |2013-11-08 |  USD  | NULL   | NULL    | 0.814    |
+---------+-----------+-------+--------+---------+----------+   
| 2       |2013-11-08 |  GBP  | NULL   | NULL    | 0.114    |
+---------+-----------+-------+--------+---------+----------+

使用主键作为 EntryID 我试图获得如下所示的输出;

+-----------+-------+-------+
| RegDate   |  USD  |  GBP  |
+-----------+-------+-------+
|2013-11-08 | 0.814 | 0.114 |
+---------+---------+-------+ 
4

4 回答 4

2
SELECT RegDate,
       SUM(CASE WHEN Code='USD' THEN Averages ELSE 0 END) as USD,
       SUM(CASE WHEN Code='GBP' THEN Averages ELSE 0 END) as GBP
FROM T
GROUP BY RegDate

SQLFiddle 演示

于 2013-11-08T05:45:23.233 回答
0

尝试:

SELECT EntryID, regDate,
SUM(CASE Code WHEN 'USD' THEN Averages ELSE 0 END) as USD,
SUM(CASE Code WHEN 'GBP' THEN Averages ELSE 0 END) as GBP
FROM TableA
GROUP BY regDate

演示

于 2013-11-08T05:53:19.700 回答
0
SELECT USD.RegDate, USD.Averages as USD,
GBP.Averages as GBP From
(SELECT RegDate, Averages
From Table1 where Code = 'USD') USD
Inner join
(SELECT RegDate, Averages
From Table1 where Code = 'GBP') GBP
ON USD.RegDate = GBP.RegDate

样品小提琴

于 2013-11-08T05:36:14.720 回答
0

您可以简单地JOIN使用表格,为您需要的每种货币使用一次表格;

SELECT usd.RegDate, usd.averages USD, gbp.averages GBP
FROM Table1 usd
JOIN Table1 gbp
  ON usd.regdate = gbp.regdate
 AND usd.code = 'USD'
 AND gbp.code = 'GBP';

一个用于测试的 SQLfiddle

请注意,此查询假定每种货币在每个日期仅存在一次以提供良好的结果,如果不是这种情况,则应将其添加到示例数据中。

于 2013-11-08T05:40:52.307 回答