如何将这两个查询合并为1?两者都使用2个不同的数据库,但都在同一台服务器上。我会在这里使用子选择或联合吗?
我基本上想要显示以下内容:
User name | Total A | Total B
jon 5 3
tim 4 2
sarah 3 1
以下是查询:
首先查询:
SELECT
U.USR_USERNAME AS `User Name`,
COUNT(rp_workflow.PIG.APP_UID) AS 'Total A'
FROM
rp_workflow.PMT_INSP_GRID PIG
JOIN
rp_workflow.PMT_INSP_NORMAL PIN
ON PIG.APP_UID = PIN.APP_UID
JOIN
wf_workflow.USERS U
ON PIN.USR_UID_ORDER = U.USR_UID
GROUP BY
U.USR_USERNAME
第二次查询:
SELECT
U.USR_USERNAME AS `User Name`,
COUNT(rp_workflow.PIQG.APP_UID) AS 'Total B'
FROM
rp_workflow.PMT_INSP_QC_GRID PIQG
JOIN
rp_workflow.PMT_INSP_NORMAL PIN
ON PIQG.APP_UID = PIN.APP_UID
JOIN
wf_workflow.USERS U
ON PIN.USR_UID_QC = U.USR_UID
WHERE
PIN.APP_STATUS = 'Completed'
GROUP BY
U.USR_USERNAME
编辑:尝试了一个子选择,但最终只显示了第二个查询的所有值的总和。感觉我很亲密,但也变得更加困惑。
SELECT
U.USR_USERNAME AS `User Name`,
COUNT(rp_workflow.PIG.APP_UID) AS 'Total A',
(SELECT
COUNT(rp_workflow.PIQG.APP_UID)
FROM
rp_workflow.PMT_INSP_QC_GRID PIQG
JOIN
rp_workflow.PMT_INSP_NORMAL PIN
ON PIQG.APP_UID = PIN.APP_UID
JOIN
wf_workflow.USERS U
ON PIN.USR_UID_QC = U.USR_UID
WHERE
PIN.APP_STATUS = 'Completed') AS 'Total B'
FROM
rp_workflow.PMT_INSP_GRID PIG
JOIN
rp_workflow.PMT_INSP_NORMAL PIN
ON PIG.APP_UID = PIN.APP_UID
JOIN
wf_workflow.USERS U
ON PIN.USR_UID_ORDER = U.USR_UID
GROUP BY
U.USR_USERNAME
它显示的内容:
User name | Total A | Total B
jon 5 6
编辑2:*表PIG或PIQG中不存在USR_UID,因此必须将它们连接到表PIN。从那里,可以检索用户名
尝试了此查询,但最终收到了一个未知的列错误:
SELECT wf_workflow.U.USR_USERNAME AS `User Name` ,
(SELECT count(PIG.APP_UID)
FROM rp_workflow.PMT_INSP_GRID PIG
JOIN rp_workflow.PMT_INSP_NORMAL PIN ON PIG.APP_UID = PIN.APP_UID
AND PIN.USR_UID_ORDER = U.USR_UID) AS 'Total A',
(SELECT count(PIQG.APP_UID)
FROM rp_workflow.PMT_INSP_QC_GRID PIQG
JOIN rp_workflow.PMT_INSP_NORMAL PIN2 ON PIQG.APP_UID = PIN2.APP_UID
AND PIN2.USR_UID_ORDER = wf_workflow.U.USR_UID
WHERE PIN2.APP_STATUS = 'Completed') AS 'Total B'
FROM wf_workflow.USERS U
答案 0 :(得分:0)
尝试
SELECT username,
SUM(CASE WHEN source = 1 THEN total END) total_a,
SUM(CASE WHEN source = 2 THEN total END) total_b
FROM
(
SELECT 1 source,
u.usr_username username,
COUNT(pig.app_uid) total
FROM rp_workflow.pmt_insp_grid pig JOIN rp_workflow.pmt_insp_normal pin
ON pig.app_uid = pin.app_uid JOIN wf_workflow.users u
ON pin.usr_uid_order = u.usr_uid
GROUP BY u.usr_username
UNION ALL
SELECT 2 source,
u.usr_username username,
COUNT(piqg.app_uid) total
FROM rp_workflow.pmt_insp_qc_grid piqg JOIN rp_workflow.pmt_insp_normal pin
ON piqg.app_uid = pin.app_uid JOIN wf_workflow.users u
ON pin.usr_uid_qc = u.usr_uid
WHERE pin.app_status = 'Completed'
GROUP BY u.usr_username
) q
GROUP BY username