我有一长串股票收益表,大约有20只股票。股票代码是一个类别。例如,假设该表具有:[日期,关闭,交易品种],其中有20,000行包含20种不同的股票交易品种。
|Date . |Close|Symbol|
|2010-01-01|20.10|SPY|
|2010-01-02|20.11|SPY|
|2010-01-02|30.11|CWGIX|
|2010-01-02|40.10|PG|
|2010-01-03|32.10|CWGIX|
|2010-01-04|41.10|PG|
|2010-01-04|30.02|CWGIX|
问题在于所有股票的起止日期都不同。如果要查找同一天发生的两只股票的收盘价,则必须运行:
SELECT
spy.Date, cwgix.Close cwgix, spy.Close spy
FROM (
SELECT DATE(Date) Date, Close FROM `mytable` WHERE Symbol = "CWGIX ORDER BY Date ASC) cwgix
JOIN (
SELECT DATE(Date) Date, Close FROM `mytable` WHERE Symbol = "SPY" ORDER BY Date ASC) spy
ON
cwgix.Date = spy.Date
这给了我
|Date |SPY |CWGIX|PG |
|2010-01-02|20.11|30.11|40.10|
等
如何对所有20只股票执行此操作?我在想有一种更好的方法来完成此任务。
答案 0 :(得分:1)
以下是用于BigQuery标准SQL
#standardSQL
SELECT Date,
MAX(IF(Symbol = 'SPY', Close, NULL)) SPY,
MAX(IF(Symbol = 'CWGIX', Close, NULL)) CWGIX,
MAX(IF(Symbol = 'ABC', Close, NULL)) ABC,
MAX(IF(Symbol = 'XYZ', Close, NULL)) XYZ
FROM `project.dataset.table`
GROUP BY Date
您将需要上面脚本中的下面几行与您拥有的所有符号一样多-这是您在问题中所说的20
MAX(IF(Symbol = 'SymbolName', Close, NULL)) SymbolName,
我对两者都感兴趣
如果仅需要所有符号都具有结束值的日期-您可以在下面使用
#standardSQL
SELECT * FROM (
SELECT DATE,
MAX(IF(Symbol = 'SPY', Close, NULL)) SPY,
MAX(IF(Symbol = 'CWGIX', Close, NULL)) CWGIX,
MAX(IF(Symbol = 'PG', Close, NULL)) PG
FROM `project.dataset.table`
GROUP BY DATE) t
WHERE NOT TO_JSON_STRING(t) LIKE '%null%'
您可以使用问题中的示例数据来测试,玩游戏,如下例所示
#standardSQL
WITH `project.dataset.table` AS (
SELECT DATE '2010-01-01' DATE, 20.10 Close, 'SPY' Symbol UNION ALL
SELECT '2010-01-02', 20.11, 'SPY' UNION ALL
SELECT '2010-01-02', 30.11, 'CWGIX' UNION ALL
SELECT '2010-01-02', 40.10, 'PG' UNION ALL
SELECT '2010-01-03', 32.10, 'CWGIX' UNION ALL
SELECT '2010-01-04', 41.10, 'PG' UNION ALL
SELECT '2010-01-04', 30.02, 'CWGIX'
)
SELECT * FROM (
SELECT DATE,
MAX(IF(Symbol = 'SPY', Close, NULL)) SPY,
MAX(IF(Symbol = 'CWGIX', Close, NULL)) CWGIX,
MAX(IF(Symbol = 'PG', Close, NULL)) PG
FROM `project.dataset.table`
GROUP BY DATE) t
WHERE NOT TO_JSON_STRING(t) LIKE '%null%'
有结果
Row DATE SPY CWGIX PG
1 2010-01-02 20.11 30.11 40.1