0

我构建了三个 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
4

1 回答 1

0

Don't double count:

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
于 2013-04-07T04:55:56.857 回答