如何在 group_concat 中使用求和和联接

How to use sum and joins within group_concat

我有两个 table,CustomerCategories 和 Articles。两个 table 都有一个名为 VatPercentage 和 VatPrice 的列。

场景:

示例tables:

文章数:

ArticleId       TotalPrice      VatPercentage    VatPrice
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
6                   0           0                0

客户类别:

CustomerCategoryId  TotalPrice  VatPercentage   VatPrice
2                   163         8.0000000000    13
2                   163         13.0000000000   13
2                   163         0               0
2                   150         25.0000000000   37.5

在这种情况下,我希望从查询返回的结果:

{esc}{40h}25 %{esc}{41h}82.5 NOK{lf}{esc}{40h}8 %{esc}{41h}22.6 NOK{lf}{esc}{40h}13 %{esc}{41h}13 NOK{lf}

我尝试过但没有任何积极结果的代码是:

SELECT GROUP_CONCAT(Result, '|') Results
FROM (
   select case when cc.VatPercentage = a.VatPercentage 
   then
   SELECT '{esc}{40}' || CAST(cc.VatPercentage AS INTEGER) || '% ' ||
           (SUM(cc.VatPrice) + SUM(a.VatPrice)) || ' NOK' || '{lf}' Result    end
else
   (
     case when cc.VatPercentage <> a.VatPercentage
       then 
       SELECT '{esc}{40}' || CAST(cc.VatPercentage AS INTEGER) || '% ' ||
           (SUM(cc.VatPrice) + SUM(a.VatPrice)) || ' NOK' || '{lf}' ||
           SELECT '{esc}{40}' || CAST(a.VatPercentage AS INTEGER) || '% ' ||
           (SUM(a.VatPrice)) || ' NOK' || '{lf}' Result 
      end
   )
FROM CustomerCategories cc
LEFT JOIN Articles a
  on cc.VatPercentage = a.VatPercentage
WHERE 
  cc.VatPercentage != '0' 
  AND a.VatPercentage != '0'
  AND cc.TotalPrice != '0'
  AND a.TotalPrice != '0'
  GROUP BY 
    cc.VatPercentage OR a.VatPercentage) x

不胜感激。

Fiddle

首先,combine两个表:

SELECT VatPercentage, VatPrice FROM CustomerCategories
UNION ALL
SELECT VatPercentage, VatPrice FROM Articles
VatPercentage   VatPrice
8.0000000000    13
13.0000000000   13
0               0
25.0000000000   37.5
25.0000000000   25
25.0000000000   20
8.0000000000    4
8.0000000000    5.6
0               0
0               0

然后对其进行简单的 GROUP BY:

SELECT VatPercentage,
       SUM(VatPrice) AS PriceSum
FROM (SELECT VatPercentage, VatPrice FROM CustomerCategories
      UNION ALL
      SELECT VatPercentage, VatPrice FROM Articles)
WHERE VatPercentage != '0'
GROUP BY VatPercentage

然后转义字符会弄乱结果:

SELECT GROUP_CONCAT('{esc}{40h}' || VatPercentage || ' %' ||
                    '{esc}{41h}' || VatPrice      || ' NOK{lf}',
                    '')
FROM (SELECT VatPercentage,
             SUM(VatPrice) AS PriceSum
      FROM (SELECT VatPercentage, VatPrice FROM CustomerCategories
            UNION ALL
            SELECT VatPercentage, VatPrice FROM Articles)
      WHERE VatPercentage != '0'
      GROUP BY VatPercentage)