子组数据的LOBase HSQL子查询

时间:2014-07-15 06:36:30

标签: sql database hsqldb libreoffice-base

我有一个自行车骑行数据库,我用它来学习使用Libreoffice Base和HSQL的SQL。该数据库由一个包含以下列的表组成:Index,Date,Bike,Miles。

我想做的是为我的公路自行车创建一个列有自行车骑行总和的列,另一个用于我的mtn自行车。我从子查询开始,但这给了我整个数据库的总数。这是我的公路自行车代码,另一个子查询将用于mtn自行车列:

SELECT YEAR( "RideDate" ) AS "Year", SUM( "Miles" ) AS "Miles", 
( SELECT SUM( "Miles" ) FROM "BikeDate" 
   WHERE( "Bike" = 'Fuji' OR "Bike" = 'Yfoil' )) AS "% Miles" 
FROM "BikeDate" AS "BikeDate" 
GROUP BY YEAR( "RideDate" ) 
ORDER BY YEAR( "RideDate" ) DESC

由于我按年分组,如何获得每个分组元素的总和 - >年?我为不知道正确的术语而道歉。我也不想做一个简单的总和,我按年和自行车分组,我有。我想用where子句打破年份。戴夫,感谢任何帮助。 LOBase 4.2.3.3。

1 个答案:

答案 0 :(得分:0)

让我根据您的真实需要提出两种可能性,以便像原始帖子一样返回值:

SELECT 
   YEAR( "RideDate" ) AS "Year", 
   SUM( "Miles" ) AS "Miles", 
   SUM(CASE WHEN "Bike" = 'Fuji' OR "Bike" = 'Yfoil' THEN "Miles" ELSE 0 END) as "% Miles"
FROM "BikeDate" AS "BikeDate" 
GROUP BY YEAR( "RideDate" ) 
ORDER BY YEAR( "RideDate" ) DESC

为了创建一个额外的列,它真正计算了百分比。 。 。类似的东西:

SELECT 
   YEAR( "RideDate" ) AS "Year", 
   SUM( "Miles" ) AS "Miles", 
   SUM(CASE WHEN "Bike" = 'Fuji' OR "Bike" = 'Yfoil' THEN "Miles" ELSE 0 END) as "Miles_Fuji_Yfoil",
   SUM(CASE WHEN "Bike" = 'Fuji' OR "Bike" = 'Yfoil' THEN "Miles" ELSE 0 END) * 100.0000000 / SUM("Miles") as "Pct_Miles_Fuji_Yfoil"
FROM "BikeDate" AS "BikeDate" 
GROUP BY YEAR( "RideDate" ) 
ORDER BY YEAR( "RideDate" ) DESC

解释:这使用HSQL函数 CASE WHEN。 。 。要么 。 。 。值ELSE 0 END 所以它只会 SUM (聚合函数)这些值。