我从未对联合查询进行过计数,并且遇到了正确完成问题的问题。
我正在运行以下查询:
SELECT *
FROM
(
SELECT vg.vertrekluchthaven AS code, count(*) as countv
FROM tbl_vluchtgegevens vg
WHERE vg.vertrekdatum2 <=NOW()
GROUP BY vg.vertrekluchthaven
UNION
SELECT vg.aankomstluchthaven AS code, count(*) as counta
FROM tbl_vluchtgegevens vg
WHERE vg.vertrekdatum2 <=NOW()
GROUP BY vg.aankomstluchthaven
) vg
INNER JOIN tbl_luchthaven lh
ON lh.luchthavenID = vg.code
GROUP BY vg.code
ORDER BY lh.luchthavencode;
最终,我正在寻找如何计算每个联合查询中的每个代码的计数。当我运行代码时,我得到countv的计数,但我没有得到任何计数。
这是我正在寻求的:
+-------+-----------+-----------+-----------+
| CODE | Name | count v | count a |
+-------+-----------+-----------+-----------+
| AMS | LONG NAME | 5 | 8 |
| MSP | LONG NAME | 5 | 2 |
| WAS | LONG NAME | 2 | 0 |
+-------+-----------+-----------+-----------+
答案 0 :(得分:0)
您需要将两个计数放在不同的列中,以便在分组时将它们分开。然后使用MAX()
获取每个的非零数。
SELECT code, name, MAX(countv) countv, MAX(counta) counta
FROM (
SELECT vg.vertrekluchthaven AS code, count(*) as countv, 0 as counta
FROM tbl_vluchtgegevens vg
WHERE vg.vertrekdatum2 <=NOW()
GROUP BY vg.vertrekluchthaven
UNION
SELECT vg.aankomstluchthaven AS code, 0 as countv, count(*) as counta
FROM tbl_vluchtgegevens vg
WHERE vg.vertrekdatum2 <=NOW()
GROUP BY vg.aankomstluchthaven
) vg
INNER JOIN tbl_luchthaven lh
ON lh.luchthavenID = vg.code
GROUP BY vg.code
ORDER BY lh.luchthavencode;
答案 1 :(得分:0)
您正在使用'tbl_luchthaven'加入联合查询的结果。也许你的代码中没有任何记录,因此最终结果集中给定代码不会显示任何行。