【问题标题】:Conditional Summing in SQL with special output具有特殊输出的 SQL 条件求和
【发布时间】:2021-04-21 17:01:26
【问题描述】:

我需要创建一个 SQL 选择语句,但遇到了一些问题。也许有人可以帮忙。我的桌子看起来像这样:

Article Name Amount Location Count
A0 Name0 10 99 1
A0 Name0 50 44 1
A0 Name0 20 44 1
A1 Name1 300 44 1
A1 Name1 250 110 1
A2 Name2 10 99 0
A3 Name3 20 1000 1
A4 Name4 NULL NULL 1

如果 count = 1,我需要做一个 select 语句来总结特定位置每篇文章的数量。我的想法是做这样的事情:

SELECT article, name, sum(amount), location
FROM test
WHERE count = 1
  AND (location IN (44, 99)
  OR location IS NULL)
GROUP BY article, name, location;

这将导致如下结果:

ARTICLE NAME SUM(AMOUNT) LOCATION
A0 Name0 70 44
A0 Name0 10 99
A4 Name4 - -
A1 Name1 300 44

唯一的问题是,我还需要输出表中数量和位置为 0 或 NULL 的文章 A3。所以如果位置44或99没有找到商品,该行不能省略,包含数量0和位置0。但如果位置99或44有产品,则不能有额外的行,数量为0和位置0。位置 0。

这甚至可以用 SQL 实现吗?非常感谢您的回答!

【问题讨论】:

  • 请解释逻辑。

标签: sql oracle


【解决方案1】:

两个SELECT 语句中的UNION 怎么样?

  • 1st 返回“正常”数据(满足您提到的条件的行;count = 1location is 44 or 99
  • 第二次返回count is 1,但location 不匹配的行(NOT EXISTS 子句)

类似这样的:

SQL> select t.article, t.name, sum(t.amount) amount, t.location
  2  from test t
  3  where t.count = 1
  4    and t.location in (44, 99)
  5  group by t.article, t.name, t.location
  6  union all
  7  select t.article, t.name, sum(t.amount) amount, null
  8  from test t
  9  where t.count = 1
 10    and not exists (select null from test a
 11                    where a.name = t.name
 12                      and a.location in (44, 99)
 13                   )
 14  group by t.article, t.name, t.location
 15  order by article, name, location;

ARTICLE    NAME      AMOUNT   LOCATION
---------- ----- ---------- ----------
A0         Name0         70         44
A0         Name0         10         99
A1         Name1        300         44
A3         Name3         20
A4         Name4

SQL>

【讨论】:

    【解决方案2】:

    您可以使用条件聚合:

    SELECT article, name,
           sum(case when count = 1 and (location in (44, 99) or location is null) then amount end),
           location
    FROM test
    GROUP BY article, name, location;
    

    【讨论】:

    • 感谢您的快速回答,但这会添加如下行:| A1 |姓名1 | - | 110 |由于 A1 已经是 listet,因此不应显示此行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多