使用 sum withinin group_concat

Using of sum withinin group_concat

假设我有一个 table,产品。这包含几个具有不同增值税百分比和增值税价格的产品:

产品

ArticleId | Price | VatPercentage | VatPrice
(integer) (numeric)   (varchar)    (numeric)
--------------------------------------------
    1       100     25.0000000000     25 
    2        80     25.0000000000     20 
    3        50      8.0000000000     4 
    4        70      8.0000000000     5.6 
    5        20           0           0
    0

现在我需要使用 Group_concat 构建字符串并按 vatpercentage 对价格求和,其中 VatPrice 不为 0 且价格不为 0。

本例中我想要返回的结果:

{a}25{b}45 SEK{c}{a}8{b}9.6 SEK{c}

我试过的代码:

select 
group_concat('{a}' || 
CAST(VatPercentage as integer) ||
'{b}' || SUM(VatPrice) || 
' SEK' || '{c}','') 
FROM Product 
group by VatPercentage
having Count(Price) > 0

Fiddle

感谢正手

在子查询中进行常规连接,然后在外部查询中使用 GROUP_CONCAT,因为您不能在另一个参数中使用一个聚合函数。

SELECT GROUP_CONCAT(Result, '|') Results
FROM (
    SELECT 'VatPercentage:' || CAST(VatPercentage AS INTEGER) || '% VatPrice: '
        || SUM(VatPrice) Result
    FROM Product
    WHERE VatPercentage != '0'
    GROUP BY VatPercentage) x

您也不需要 HAVING 子句。这只是排除了所有 Price 值为 NULL 的结果。但是您的示例结果跳过了 VatPercentage 为零的行,因此我将其放在 WHERE 子句中。

DEMO