CASE语句中的MYSQL SUM 2值

时间:2018-04-30 13:06:40

标签: mysql sql

您好我有以下查询

public class PathNames {
    private string _pathA = "Some Path";
    private string _pathB = "Another Path";

    public string BaseDirectoryPath { 
        get {
            return Path.Combine(_pathA, _pathB);
        }
        set {
            //No OP
        }
    }
}

目前此查询产生以下结果

SELECT 
ORG.`id`,

ORG.`organisation_name`,

SFCR.report_date_year 

,CASE 
    -- GWP
    WHEN (QRT_VALUES.`template_id` = 'S.05.01.02.01' AND QRT_VALUES.`row_id` = 'R0110' AND QRT_VALUES.`column_id` = 'C0200') THEN 'gross_written_premiums' 

    WHEN (QRT_VALUES.`template_id` = 'S.05.01.02.02' AND QRT_VALUES.`row_id` = 'R1410' AND QRT_VALUES.`column_id` = 'C0300') THEN 'gross_written_premiums' 

END AS Dimension 
,CASE
    -- GWP
    WHEN (QRT_VALUES.`template_id` = 'S.05.01.02.01' AND QRT_VALUES.`row_id` = 'R0110' AND QRT_VALUES.`column_id` = 'C0200' || 
          QRT_VALUES.`template_id` = 'S.05.01.02.02' AND QRT_VALUES.`row_id` = 'R1410' AND QRT_VALUES.`column_id` = 'C0300') 
    THEN  
        (
            (CASE 
                WHEN (QRT_VALUES.`template_id` = 'S.05.01.02.01' AND QRT_VALUES.`row_id` = 'R0110' AND QRT_VALUES.`column_id` = 'C0200') 
                THEN (QRT_VALUES.`value`) ELSE 0 END)
            +

            (CASE 
                WHEN (QRT_VALUES.`template_id` = 'S.05.01.02.02' AND QRT_VALUES.`row_id` = 'R1410' AND QRT_VALUES.`column_id` = 'C0300') 
                THEN (QRT_VALUES.`value`) ELSE 0 END)
        )

END AS Value,  

ORG.`parent_id` AS `parent_id`

FROM ird_qrt_values AS QRT_VALUES

LEFT JOIN `ird_reports` AS SFCR ON (QRT_VALUES.`report_id` = SFCR.`id` AND SFCR.`report_type_id` = 1)

LEFT JOIN `ird_organisations` AS ORG ON (SFCR.`organisation_id` = ORG.`id` AND SFCR.`report_type_id` = 1)

WHERE 
-- GWP
(QRT_VALUES.`template_id` = 'S.05.01.02.01' AND QRT_VALUES.`row_id` = 'R0110' AND QRT_VALUES.`column_id` = 'C0200') OR

(QRT_VALUES.`template_id` = 'S.05.01.02.02' AND QRT_VALUES.`row_id` = 'R1410' AND QRT_VALUES.`column_id` = 'C0300') AND 
SFCR.`qrt_processed` = 1 

HAVING organisation_name = 'Aviva Plc';

我正在寻找的是每年2行数的总和为一行。见下表。我不确定如何在案例陈述中这样做。

id      organisation_name       report_date_year        Dimension                       Value
-------------------------------------------------------------------------------------------------------
351     Aviva Plc               2016                    gross_written_premiums          15672717.000
351     Aviva Plc               2016                    gross_written_premiums          9708280.000
351     Aviva Plc               2017                    gross_written_premiums          8234725.034
351     Aviva Plc               2017                    gross_written_premiums          9150979.428

非常感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT id, organisation_name, report_date_year, Dimension, SUM(Value) Value
FROM
(<Your current Query>) t
GROUP BY
id, organisation_name, report_date_year, Dimension