oracle 如何在多个列上编写具有不同条件的查询?

8qgya5xd  于 2023-11-17  发布在  Oracle
关注(0)|答案(3)|浏览(193)

| ORG|销售ID|电荷|月|
| --|--|--|--|
| AA| 1 | 20 |Nov|
| AA| 2 | 30 |Dec|
| BB| 1 | 20 |Dec|
| BB| 2 | 00 |Dec|
| BB| 3 | 00 |Dec|
| BB| 1 | 20 |Nov|
| BB| 2 | 00 |Nov|
| CC| 3 | 00 |Dec|
我有一个扩展版本的上述表格。基本上,我希望找到的ORG的所有其他收费的总和销售ID不是1的记录是零,相对于每个月。
因此,对于结果,我想有一些类似于下面关于上表:
| ORG|月|
| --|--|
| BB| Nov|
| BB| Dec|
| CC| Dec|
我尝试了各种各样的查询,但这是最新的一个:

SELECT "MONTH", "ORG"
FROM 
  (SELECT DISTINCT "MONTH" , "CHARGE", "SALE_ID" ,"ORG" 
  CASE WHEN "SALE_ID" != 1  AND "SALE_ID" IS NOT NULL AND SUM("CHARGE") OVER(PARTITION BY "ORG", "MONTH" )=0
THEN "ORG" END 
  FROM "TABLE" WHERE 
"MONTH" >= '01-JAN-2023'  )
GROUP BY    "MONTH", "ORG"

字符串

bqjvbblv

bqjvbblv1#

你走在正确的道路上,但还有一些问题。
1.子查询缺少别名

  1. Case语句未用于生成新列。
    1.根据您的月份列“2023年1月1日”,这将不起作用。
    我已经重写了你的查询,它看起来应该像这样。你可能需要修改过滤。
WITH cte
AS (
    SELECT "ORG"
        ,"MONTH"
        ,SUM(CASE WHEN "SALE_ID" != 1 THEN "CHARGE"
                ELSE 0 END) AS OtherCharges
        ,MAX(CASE WHEN "SALE_ID" = 1 THEN "CHARGE"
                ELSE 0 END) AS Sale1Charge
    FROM "TABLE"
    WHERE "MONTH" IN ('NOV','DEC', '...')
    GROUP BY "ORG","MONTH"
    )
SELECT "ORG","MONTH"
FROM cte
WHERE OtherCharges = 0 AND Sale1Charge > 0

字符串

wztqucjr

wztqucjr2#

使用HAVING子句和条件聚合:

SELECT org,
       month
FROM   table_name
GROUP BY
       org, month
HAVING SUM(CASE WHEN sale_id != 1 THEN charge END) = 0

字符串
其中,对于样本数据:

CREATE TABLE table_name (ORG, SALE_ID, CHARGE, MONTH) AS
SELECT 'AA', 1, 20, 'NOV' FROM DUAL UNION ALL
SELECT 'AA', 2, 30, 'DEC' FROM DUAL UNION ALL
SELECT 'BB', 1, 20, 'DEC' FROM DUAL UNION ALL
SELECT 'BB', 2, 00, 'DEC' FROM DUAL UNION ALL
SELECT 'BB', 3, 00, 'DEC' FROM DUAL UNION ALL
SELECT 'BB', 1, 20, 'NOV' FROM DUAL UNION ALL
SELECT 'BB', 2, 00, 'NOV' FROM DUAL UNION ALL
SELECT 'CC', 3, 00, 'DEC' FROM DUAL;


产出:
| ORG|月|
| --|--|
| CC| Dec|
| BB| Nov|
| BB| Dec|
fiddle

6ojccjat

6ojccjat3#

比如说:

SELECT "MONTH" , "ORG" 
FROM "TABLE" 
WHERE "SALE_ID" != 1
GROUP BY "MONTH" , "ORG"
HAVING sum("CHARGE") = 0

字符串

相关问题