0

我有一个骑自行车的数据库,我用它来学习使用 Libreoffice Base 和 HSQL 的 SQL。该数据库由一个表组成,其中包含以下列:索引、日期、自行车、里程。

我想做的是为我的公路自行车和我的 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 。

4

1 回答 1

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

为了创建一个额外的列,它真正计算 Percent 。. . 就像是:

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。. . 或者 。. . value ELSE 0 END所以它只会对这些值求和(聚合函数)。

于 2014-07-15T14:55:41.537 回答