简体   繁体   English

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

[英]how to combine results of two different queries from one table mysql

I am using MySQL in phpMyAdmin, I have a table from which I am trying to get the following result as illustrated below: 我在phpMyAdmin中使用MySQL,我有一个表,试图从中获得以下结果,如下所示:

I have a table Rate structured as follows; 我有一个表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    |
+---------+-----------+-------+--------+---------+----------+

With the primary key as EntryID I am trying to get the output as shown below; 使用主键作为EntryID,我试图获得如下所示的输出;

+-----------+-------+-------+
| RegDate   |  USD  |  GBP  |
+-----------+-------+-------+
|2013-11-08 | 0.814 | 0.114 |
+---------+---------+-------+ 
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 SQLFiddle演示

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 样品小提琴

You can simply JOIN the table with itself, use the table once for each currency you need; 您可以简单地将表本身与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 . 要使用进行测试的SQLfiddle

Note that this query assumes that each currency exists exactly once per date to give a good result, if that's not the case, you should add that to your sample data. 请注意,此查询假定每种货币每个日期恰好存在一次,以提供良好的结果,如果不是这种情况,则应将其添加到样本数据中。

Try: 尝试:

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

See Demo 观看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM