我构建了三个SQL查询,它们对一组约八个表进行操作。三个中的每一个在其group by子句中具有相同的参数。我正在尝试合并这三个查询,以生成单个输出表,虽然我尝试的所有内容似乎都打破了工作基础查询。
我想要一个看起来像的输出
[heading] [query1 output column] [query2 output column] [query3 output column]
,[heading]列是三个现有查询的group by子句中使用的现有参数。
我意识到我在这里展示了我的新意,虽然我被卡住了,并且在同一个错误的圈子里走了太多次......
编辑 *
我认为代码片段会让人感到困惑,尽管这是一个略微缩写的版本;
SELECT
TITLE_COUNT.index,
COUNT (TITLE_COUNT.TTOTAL) AS TITLES,
COUNT (AUTHOR_COUNT.TTOTAL) AS AUTHOR
FROM(
SELECT
index, title, date,
COUNT (*) AS TTOTAL
FROM (SELECT DISTINCT index, title, date FROM TableP P) P
GROUP BY
index, title, date
ORDER BY
index
) AS TITLE_COUNT,
(
SELECT
index,
COUNT (*) AS TTOTAL
FROM (SELECT DISTINCT index, FROM TableM M) M
GROUP BY
index
ORDER BY
index
) AS AUTHOR_COUNT
WHERE
TITLE_COUNT.index = AUTHOR_COUNT.index
GROUP BY
TITLE_COUNT.index
;
我的问题是,输出表中的计数列已成倍增加。例如,站在查询中给我一些类似
的内容TITLE
index count
001 12
002 10
003 15
AUTHOR
index count
001 2
002 4
003 6
虽然上面的查询结果是
001 24
002 40
003 90
答案 0 :(得分:0)
不要重复计算:
SELECT
TITLE_COUNT.index,
TITLE_COUNT.TTOTAL AS TITLES,
AUTHOR_COUNT.TTOTAL AS AUTHOR
FROM(
SELECT
index, title, date,
COUNT (*) AS TTOTAL
FROM (SELECT DISTINCT index, title, date FROM TableP P) P
GROUP BY
index, title, date
ORDER BY
index
) AS TITLE_COUNT
FULL OUTER JOIN (
SELECT
index,
COUNT (*) AS TTOTAL
FROM (SELECT DISTINCT index, FROM TableM M) M
GROUP BY
index
ORDER BY
index
) AS AUTHOR_COUNT
ON TITLE_COUNT.index = AUTHOR_COUNT.index
GROUP BY
TITLE_COUNT.index