gpt4 book ai didi

sqlite - 如何在group_concat中使用sum和joins

转载 作者:行者123 更新时间:2023-12-03 19:41:29 27 4
gpt4 key购买 nike

我有两个表,CustomerCategories和Articles。这两个表都有一个称为VatPercentage和VatPrice的列。

场景:


如果两个表中存在相同的增值税百分比,我想对两个表中的增值税价格求和并将其添加到字符串中。
如果增值税百分比仅存在于CustomerCategories表中,我想从此处汇总增值税价格并将其添加到字符串中。
如果增值税百分比仅存在于“商品”表中,则我想从此处汇总增值税价格并将其添加到字符串中。


表格示例:

文章:

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   VatPrice8.0000000000    1313.0000000000   130               025.0000000000   37.525.0000000000   2525.0000000000   208.0000000000    48.0000000000    5.60               00               0

Then do a simple GROUP BY over that:

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)

关于sqlite - 如何在group_concat中使用sum和joins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28262040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com