如何从一个表mysql中组合两个不同查询的结果

时间:2013-11-08 05:30:07

标签: mysql

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

我有一个表格结构如下;

+---------+-----------+-------+--------+---------+----------+
| 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 个答案:

答案 0 :(得分: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 demo

答案 1 :(得分: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

<强> Sample Fiddle

答案 2 :(得分: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';

An SQLfiddle to test with

请注意,此查询假设每个货币每个日期只存在一次以产生良好的结果,如果不是这种情况,则应将其添加到样本数据中。

答案 3 :(得分: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

请参阅Demo