2014-07-15 71 views
0

我有一個我使用Libreoffice Base和HSQL學習SQL的自行車遊樂設施數據庫。該數據庫包含一個表格,其中包含索引,日期,自行車,英里等列。子組數據的LOBase HSQL子查詢

我想要做的是創建一個列,每年的自行車遊樂設施爲我的公路自行車和另一個我的自行車。我從一個子查詢總數開始,但是這給了我一個整個數據庫的總數。這是我爲公路自行車碼,另一個子查詢將被用於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。

回答

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(聚合函數)這些值。