substring:行信息到字段名称

时间:2017-12-03 16:27:25

标签: sqlite subquery

我在SQLite数据库中有信息。数据库结构无法更改。

Illustration

我正在尝试构建一个查询,该查询将为我提供TypeOfInformation条目为字段名称的结果:

Illustration

我的第一次尝试是使用子查询:

SELECT (SELECT Value FROM FinData WHERE Type = 'Price') AS Price,
       (SELECT Value FROM FinData WHERE Type = 'Volume') AS Volume
FROM FinData")

看似完美,但结果是一个结果集,其中PriceVolume列中的每个条目都等于PriceVolume的第一个条目在原始数据库中:

Illustration

我试图绕过这个并包含其他价格和体积信息 - 但我失败了。 (遗憾的是,因为语法似乎很容易掌握。)

接下来尝试以下内容:

Select Date, Value AS Volume From FinData WHERE Volume IN 
(SELECT Value FROM FinData WHERE (Type = 'Volume'))

这为我提供了一个包含Volume列和所有卷信息的结果集。好的,到目前为止。但是,当我想补充这个结果集时,Price列通过

Select Date, Value AS Volume From FinData WHERE Volume IN 
(SELECT Value FROM FinData WHERE (Type = 'Volume'))
union
Select Date, Value AS Close From FinData WHERE Price IN 
(SELECT Value FROM FinData WHERE (Type = 'Price'))

我得到的结果集只显示一列(“音量”)中的价格和音量信息,因此也没用。

2 个答案:

答案 0 :(得分:1)

要查找与外部查询中的行对应的值,您必须使用correlated subquery,它明确地在两者之间建立连接:

SELECT Date,
       (SELECT Value
        FROM FinData
        WHERE Date = Dates.Date
          AND TypeOfInformation = 'Price'
       ) AS Price,
       (SELECT Value
        FROM FinData
        WHERE Date = Dates.Date
          AND TypeOfInformation = 'Volume'
       ) AS Volume
FROM (SELECT DISTINCT Date
      FROM FinData) AS Dates;

(DISTINCT子查询用于防止每个日期有多行。)

或者,将所有行分组为日期,并使用聚合函数和CASE expressions从正确的行中提取值:

SELECT Date,
       MAX(CASE WHEN TypeOfInformation = 'Price'  THEN Value END) AS Price,
       MAX(CASE WHEN TypeOfInformation = 'Volume' THEN Value END) AS Volume
FROM FinData
GROUP BY Date;

答案 1 :(得分:0)

假设每个价格对的日期是唯一的,您可以这样做:

with xxx(date,price,volume) as
  (
   select date,value,0 from findata where typeofinformation = 'Price'
   union
   select date,0,value from findata where typeofinformation = 'Volume'
  )
  select date,sum(price) price,sum(volume) volume from xxx group by date;