gpt4 book ai didi

sql - sql中的加入计数

转载 作者:行者123 更新时间:2023-12-04 22:01:04 24 4
gpt4 key购买 nike

我对 SQL 很陌生,并且正在尝试做一些不愚蠢的事情。为了提供一些背景信息,我正在比较运营商分支中车辆的规划和实现使用,并且需要计算两者的发生情况。我有一个 with subquery as,它返回类似于以下内容的内容

PLANNED  | REALIZED
---------+----------
TRUCK | BI-TREM
TRUCK | TRUCK
TRUCK | TRUCK
TRUCK | TRUCK
TRUCK | TRUCK
CARRETA | CARRETA
CARRETA | CARRETA
TRUCK | KOMBI
TRUCK | BI-TREM
CARRETA | KOMBI
CARRETA | KOMBI
TRUCK | TRUCK
CARRETA | CARRETA
CARRETA | BI-TREM
CARRETA | CARRETA
CARRETA | CARRETA
TRUCK | BI-TREM

并想返回如下内容

VEHICLE | TOTAL_PLANNED | TOTAL_REALIZED
--------+---------------+---------------
CARRETA | 8 | 5
TRUCK | 9 | 5
BI-TREM | 0 | 4
KOMBI | 0 | 3

我尝试了以下方法

select PLANNED, 
count(*) as TOTAL_PLANNED
null as REALIZED,
0 as TOTAL_REALIZED
from subquery
group by PLANNED

union all

select null as PLANNED,
0 as TOTAL_PLANNED,
REALIZED,
count(*) as TOTAL_REALIZED
from subquery
group by REALIZED

返回

CARRETA 8   NULL    0
TRUCK 9 NULL 0
NULL 0 BI-TREM 4
NULL 0 CARRETA 5
NULL 0 TRUCK 5
NULL 0 KOMBI 3

我还使用子查询尝试了所有可用的连接,但没有成功。事实上,RIGHT JOIN 有效,但这只是因为所有计划中的车辆也都在已实现的一侧:如果有些没有,我将在 VEHICLE 列中有一个 NULL。

感谢您的帮助,即使只是指向 SQL 命令的指针。

PS.:这个查询必须同时在 SQL Server 和 Oracle 上工作,所以我正在争取纯 SQL。

最佳答案

试试:

SELECT PLANNED_REALIZED AS VEHICLE, 
SUM(TOTAL_PLANNED) AS TOTAL_PLANNED,
SUM(TOTAL_REALIZED) AS TOTAL_REALIZED
FROM
(select PLANNED AS PLANNED_REALIZED,
1 as TOTAL_PLANNED
0 as TOTAL_REALIZED
from subquery
union all
select REALIZED as PLANNED_REALIZED,
0 as TOTAL_PLANNED,
1 as TOTAL_REALIZED
from subquery
) SQ
GROUP BY PLANNED_REALIZED

关于sql - sql中的加入计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9722284/

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