简体   繁体   English

SQL为按列分组的每组行划分两个列值

[英]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' . 对于每个公司名称,都有行,其中包含company_name,price和两个日期之一,即'20011231''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. 我想提供一个查询,该查询将每个company_name组的日期'20111230'的价格除以日期'20011231'的价格。

Furthermore, I would like to delete all of the company_name rows if there aren't rows which have both dates. 此外,如果没有同时包含两个日期的行,我想删除所有company_name行。

For the first query, I tried the below code but it gave the following error: "Operand data type varchar is invalid for divide operator." 对于第一个查询,我尝试了以下代码,但它给出了以下错误:“操作数数据类型varchar对于除法运算符无效。”

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 这是SQLFiddle演示

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 这是SQLFiddle演示

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

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