将以下查询语句与上一条查询语句拼接起来select b.department_name,b.department_code,sum(zj)zj,sum(xz)xz,sum(yf)yf,sum(yj)yj from( select substr(b.department_code, 0, 4) department_code,sum(DIRECTCOST)zj, sum(MANAGERMENTSHAREDCOST) as xz, sum(MEDICALASSISTANCESHAREDCOST)as yf, sum(MEDICALTECHNOLOGYSHAREDCOST)as yj from dcm_calshare a left join dcm_department b on a.DEPT_ID=b.department_code where b.outin in ('MZ','ZY','MZZY') and yearmonth='2023-03' group by (b.department_code, 0, 4),b.outin) a left join dcm_department b on a.department_code=b.department_code where b.department_code not in('2099') group by b.department_code,b.department_name
时间: 2024-02-25 07:53:20 浏览: 119
SELECT语句的基本结构
可以使用 UNION ALL 将两条 SQL 查询语句拼接起来,从而得到一个包含所有查询结果的表格。
以下是拼接后的 SQL 查询语句:
```
SELECT b.department_name, b.department_code, a.outin, amount
FROM (
SELECT substr(b.department_code, 0, 4) department_code, b.outin, sum(amount) amount
FROM dcm_income_data a
LEFT JOIN dcm_department b ON a.ordered_dept_id = b.department_id
WHERE b.outin IN ('MZ', 'ZY', 'MZZY') AND yearmonth = '2023-03'
GROUP BY (b.department_code, 0, 4), b.outin
) a
LEFT JOIN dcm_department b ON a.department_code = b.department_code
UNION ALL
SELECT b.department_name, b.department_code, sum(zj) zj, sum(xz) xz, sum(yf) yf, sum(yj) yj
FROM (
SELECT substr(b.department_code, 0, 4) department_code, sum(DIRECTCOST) zj, sum(MANAGERMENTSHAREDCOST) xz,
sum(MEDICALASSISTANCESHAREDCOST) yf, sum(MEDICALTECHNOLOGYSHAREDCOST) yj
FROM dcm_calshare a
LEFT JOIN dcm_department b ON a.DEPT_ID = b.department_code
WHERE b.outin IN ('MZ', 'ZY', 'MZZY') AND yearmonth = '2023-03'
GROUP BY (b.department_code, 0, 4)
) a
LEFT JOIN dcm_department b ON a.department_code = b.department_code
WHERE b.department_code NOT IN ('2099')
GROUP BY b.department_code, b.department_name;
```
该查询语句首先执行两个子查询,分别获取收入数据和成本数据,并按照部门编码、收入类型和成本类型进行汇总。然后,使用 UNION ALL 将两个子查询的结果合并起来,并对合并后的结果按照部门编码和部门名称进行分组。其中,WHERE 子句用于过滤部门编码为 2099 的记录。需要注意的是,UNION ALL 会将两个子查询的结果直接合并,而不会去重,因此可能会出现重复记录。
阅读全文