简体   繁体   中英

SQL Dividing two column values for each set of rows grouped by a column

Currently, I have a table which has the following three

variables : company_name, data_date, and price.

The data contained in the table has a time-series nature. For each of the company names there are rows which have company_name, price and one of two dates, '20011231' or '20111230' .

There are no duplicates in this dataset. I would like help coming up with a query that divides the price at date '20111230' by the price at date '20011231' for each of the company_name groups.

Furthermore, I would like to delete all of the company_name rows if there aren't rows which have both dates.

For the first query, I tried the below code but it gave the following error: "Operand data type varchar is invalid for divide operator."

SELECT (SELECT prc
        FROM A_returns
        WHERE [date] = '20111230'
        GROUP BY [comnam], [PRC])/
       (SELECT prc
        FROM A_returns
        WHERE [date] = '20111230'
        GROUP BY [comnam], [PRC]) 
FROM A_returns

To remove the above error, I tried casting the values in the price column to floats but I receive the same error as before.

UPDATE A_returns
SET prc = CAST(prc AS float)
GO

You can do something like this

SELECT t1.comnam, t1.prc / t2.prc AS price_ratio
  FROM A_returns t1 JOIN A_returns t2
    ON t1.comnam = t2.comnam
   AND t1.date = '20111230'
   AND t2.date = '20111231'

Sample output:

|   COMNAM |    PRICE_RATIO |
|----------|----------------|
| company1 | 1.052631578947 |
| company2 | 0.909090909091 |

Here is SQLFiddle demo

To delete rows for companies that don't have records for both dates

DELETE t1 
  FROM A_returns t1 JOIN
(
    SELECT comnam
    FROM A_returns
    GROUP BY comnam
   HAVING COUNT(*) = 1

) t2
ON t1.comnam = t2.comnam

Here is SQLFiddle demo

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