0

我有一张如下表:

Date, Security_Name, Price
1/1/00, AAPL, 100
1/1/00, BBRY, 200
...
1/2/00, AAPL, 101
1/2/00, BBRY, 195
...

我正在尝试编写一个显示以下内容的查询:

Date, Price_AAPL, Price_BBRY
1/1/00, 100, 200
1/2/00, 101, 195

我试过这个查询...

SELECT Date, Price
FROM Table
WHERE Security_Name = "AAPL" OR Security_Name = "BBRY"

但我得到的结果就像原来的堆叠表一样。我正在考虑以某种方式复制另一行,这超出了我的能力。

4

2 回答 2

1

Using your sample data in Access 2007, the query below gives me this result set. It differs from your requested output only in the column names. If that's an issue, you could save my query and use it as the data source for another query where you alias the column names as desired.

Date      AAPL BBRY
1/1/2000   100  200
1/2/2000   101  195

And here's the SQL from my query. If it works for you after you substitute your table name for YourTable, that's great. However, you may find it useful to try creating your own similar query from scratch using Access' "Crosstab Query Wizard". It's a helpful wizard. :-)

TRANSFORM Sum(y.Price) AS SumOfPrice
SELECT y.Date
FROM YourTable AS y
WHERE (((y.Security_Name) In ("AAPL","BBRY")))
GROUP BY y.Date
PIVOT y.Security_Name;
于 2013-10-11T16:08:34.687 回答
0

尝试这个

WITH t2(dt) AS
(SELECT DISTINCT dt FROM t1)
SELECT
dt,
Price_AAPL = (SELECT price FROM t1 b WHERE b.dt = a.dt AND b.security_name = 'AAPL'),
Price_BBRY = (SELECT price FROM t1 c WHERE c.dt = a.dt AND c.security_name = 'BBRY')
FROM t2 a

WITH从句

SELECT
dt,
Price_AAPL = (SELECT price FROM t1 b WHERE b.dt = a.dt AND b.security_name = 'AAPL'),
Price_BBRY = (SELECT price FROM t1 c WHERE c.dt = a.dt AND c.security_name = 'BBRY')
FROM (SELECT DISTINCT dt FROM t1) a
于 2013-10-11T14:51:46.423 回答