dimanche 1 février 2015

How to use sum and joins within group_concat

I have two tables, CustomerCategories and Articles. Both tables have a column called VatPercentage and VatPrice.


Scenarios:



  • In case of same vatpercentage exists in both tables i want to sum the vatprice from both tables and add it to the string.

  • In case of vatpercentage only exists in CustomerCategories table i want to sum the vatprice from here and add it to the string.

  • In case of vatpercentage only exists in Articles table i want to sum the vatprice from here and add it to the string.


Example tables:


Articles:



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


CustomerCategories:



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


The result i want back from the Query in this case:



{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}


The code i've trying without any positive results is:



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


Help would be appreciated.


Fiddle


Aucun commentaire:

Enregistrer un commentaire