简体   繁体   中英

Column That Is A Ratio of Other Unique Values On Matching Dates in SQL Server

Right now I have a database that is a combination of ticker symbols, dates, and their price on that date.

A sample looks like this:

在此处输入图像描述

What I need to do is create a new table that calculates the ratio between the values for DEM and AUS when they have the same dates.

So, the example output might look like this:

在此处输入图像描述

With the following starter code, what query could I use to create the desired results?

CREATE TABLE test(
DT DATE,
Ticker varchar(10),
Price FLOAT);

INSERT INTO test VALUES(
'1-01-2020', 'DEM', 25),
('1-02-2020', 'DEM', 24),
('1-03-2020', 'DEM', 26),
('1-04-2020', 'DEM', 25),
('1-01-2020', 'AUS', 25),
('1-03-2020', 'AUS', 20),
('1-04-2020', 'AUS', 25)

You can use a join

select td.dt, td.price / ta.price as value
from test td join
     test ta
     on td.date = ta.date 
where td.ticker = 'DEM' and ta.ticker = 'AUS';

Assuming there are no duplicate tickers in the same date, you can GROUP BY date and then use conditional aggregation:

SELECT 'DA-RATIO' Name,
       DT,
       MAX(CASE WHEN Ticker = 'DEM' THEN Price END) /
       MAX(CASE WHEN Ticker = 'AUS' THEN Price END) VALUE
FROM test
WHERE Ticker IN ('DEM', 'AUS')
GROUP BY DT
HAVING COUNT(*) = 2

See the demo .
Results:

> Name     | DT         | VALUE
> :------- | :--------- | ----:
> DA-RATIO | 2020-01-01 |     1
> DA-RATIO | 2020-01-03 |   1.3
> DA-RATIO | 2020-01-04 |     1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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