如何使这个联合查询更有效率?
how to make this union query more effecient?
我在下面使用 UNION 连接创建了 SQL 查询。
如您所见,我查询了同一个 table 两次,但条件略有不同。如果 TYP 是 A 那么它就是一个 Offer。如果TYP为N,AB为真,则为订单。
一切正常。但我猜有更优雅的方式来做到这一点?我希望你能告诉我那是什么! :)
谢谢。
(顺便说一句,如果有所不同,请使用优势 sql)
SELECT
DATUM as report_month,
REGION as region,
count(DISTINCT NUMMER) as order_number,
'Offer' as Type
from xxxxxxxxxxxx
left join xxxxxxxxx on KDNR = anotherDAB.KDNR
WHERE DATUM = '2021-02-16' AND TYP = 'A'
group by report_month, region
UNION
SELECT
DATUM as report_month,
REGION as region,
count(DISTINCT NUMMER) as order_number,
'Order' as Type
from xxxxxxxxxxx
left join xxxxxxxxx on KDNR = anotherDAB.KDNR
WHERE DATUM = '2021-02-16' AND TYP = 'N' AND AB = true
group by report_month, region
我怀疑你只是想要条件聚合:
SELECT DATUM as report_month, REGION as region,
count(DISTINCT NUMMER) as order_number,
typ
from xxxxxxxxxxxx left join
xxxxxxxxx
on KDNR = KDNR
WHERE DATUM = '2021-02-16' AND
(TYP = 'A' OR TYP = 'N' AND AB = true)
GROUP BY report_month, region, type;
以上将 TYP
保留为 A
或 N
。如果需要字符串,可以使用 case
表达式:
(CASE WHEN typ = 'A' THEN 'Offer' ELSE 'Order' END)
我在下面使用 UNION 连接创建了 SQL 查询。
如您所见,我查询了同一个 table 两次,但条件略有不同。如果 TYP 是 A 那么它就是一个 Offer。如果TYP为N,AB为真,则为订单。
一切正常。但我猜有更优雅的方式来做到这一点?我希望你能告诉我那是什么! :)
谢谢。 (顺便说一句,如果有所不同,请使用优势 sql)
SELECT
DATUM as report_month,
REGION as region,
count(DISTINCT NUMMER) as order_number,
'Offer' as Type
from xxxxxxxxxxxx
left join xxxxxxxxx on KDNR = anotherDAB.KDNR
WHERE DATUM = '2021-02-16' AND TYP = 'A'
group by report_month, region
UNION
SELECT
DATUM as report_month,
REGION as region,
count(DISTINCT NUMMER) as order_number,
'Order' as Type
from xxxxxxxxxxx
left join xxxxxxxxx on KDNR = anotherDAB.KDNR
WHERE DATUM = '2021-02-16' AND TYP = 'N' AND AB = true
group by report_month, region
我怀疑你只是想要条件聚合:
SELECT DATUM as report_month, REGION as region,
count(DISTINCT NUMMER) as order_number,
typ
from xxxxxxxxxxxx left join
xxxxxxxxx
on KDNR = KDNR
WHERE DATUM = '2021-02-16' AND
(TYP = 'A' OR TYP = 'N' AND AB = true)
GROUP BY report_month, region, type;
以上将 TYP
保留为 A
或 N
。如果需要字符串,可以使用 case
表达式:
(CASE WHEN typ = 'A' THEN 'Offer' ELSE 'Order' END)