在MYSQL中加入2个不存在的表

时间:2016-03-14 14:59:19

标签: mysql join

我无法加入来自两个查询的两个表,这意味着我的数据库中没有实际的表。我有以下内容:

SELECT
    fiscalYear,
    BidOwner,
    count(cbid) AS c
FROM
    financials_tbl
GROUP BY
    BidOwner,
    fiscalYear

每年为每个BidOwner带来他/她当年的出价金额。

现在这一个:

SELECT
    fiscalYear,
    max(c)
FROM
    (
        SELECT
            fiscalYear,
            BidOwner,
            count(cbid) AS c
        FROM
            financials_tbl
        GROUP BY
            BidOwner,
            fiscalYear
    ) InputTable
GROUP BY
    fiscalYear

带来当年员工(2列)的最高出价。

我需要的是将最后一张表与前一张表中的相应出价所有者一起加入,例如vlookup,以查找每年在第二张表中显示的最高交易金额。

2 个答案:

答案 0 :(得分:2)

看起来您正试图在计数查询的结果中找到分组最大值。不幸的是,我不知道如何在不创建两个相同子查询的情况下执行此操作,但我认为这应该可行。

SELECT
    t1.fiscalYear, t1.BidOwner, t1.c
FROM
    (SELECT fiscalYear, BidOwner, count(cbid) AS c
     FROM financials_tbl
     GROUP BY BidOwner, fiscalYear) t1
LEFT JOIN
    (SELECT fiscalYear, BidOwner, count(cbid) AS c
     FROM financials_tbl
     GROUP BY BidOwner, fiscalYear) t2
ON t1.fiscalYear = t2.fiscalYear AND t1.c < t2.c
WHERE t2.BidOwner IS NULL

答案 1 :(得分:0)

您可以通过以下方式加入结果:

SELECT
t2.fiscalYear,
t2.BidOwner,
t2.c
FROM (
    SELECT
        fiscalYear,
        max(c) as max
    FROM
        (
            SELECT
                fiscalYear,
                BidOwner,
                count(cbid) AS c
            FROM
                financials_tbl
            GROUP BY
                BidOwner,
                fiscalYear
        ) InputTable
    GROUP BY
        fiscalYear
) t1
JOIN (
    SELECT
        fiscalYear,
        BidOwner,
        count(cbid) AS c
    FROM
        financials_tbl
    GROUP BY
        BidOwner,
        fiscalYear  
) t2
ON  t2.max = t1.c
AND t2.fiscalYear = t1.fiscalYear;

但是,对于大型数据集来说,这种查询的性能不会很好......