代码之家  ›  专栏  ›  技术社区  ›  Chris Betti

请解释如何使用派生表将此SQL表示为单个语句

  •  1
  • Chris Betti  · 技术社区  · 14 年前

    这里有些东西,虽然坏了,但和我想要的差不多:

    SELECT split.share, split.weight, split.creditor, split.debtor, share.amount, wsum.sum
    FROM (
        SELECT split.share, split.weight, split.creditor, split.debtor, share.amount
        FROM ( split LEFT JOIN share ON split.share = share.id )
        WHERE debtor = 6 OR creditor = 6 )
        LEFT JOIN (
            SELECT split.share, SUM(weight) AS sum
            FROM split
            GROUP BY split.share
        ) wsum
        ON split.share = wsum.share;
    

    CREATE TEMPORARY TABLE weightsum (share INT, sum INT);
    
    INSERT INTO weightsum (share, sum)
    SELECT split.share, SUM(weight) AS sum
    FROM split
    GROUP BY split.share;
    
    CREATE TEMPORARY TABLE summary (share INT, weight INT, creditor INT, debtor INT, amount DECIMAL(10,2));
    
    INSERT INTO summary (share, weight, creditor, debtor, amount)
    SELECT split.share, split.weight, split.creditor, split.debtor, share.amount
    FROM (split LEFT JOIN share ON split.share = share.id)
    WHERE debtor = 6 OR creditor = 6;
    
    SELECT summary.share, summary.weight, weightsum.sum, summary.creditor, summary.debtor, summary.amount, ((summary.amount / weightsum.sum) * summary.weight) AS split_amount
    FROM summary LEFT JOIN weightsum
    ON summary.share = weightsum.share;
    

    谢谢你的帮助。

    1 回复  |  直到 14 年前
        1
  •  0
  •   VenerableAgents    13 年前

    SELECT split.share, split.weight, split.creditor, split.debtor, share.amount, wsum.sum
    FROM (
        SELECT split.share, split.weight, split.creditor, split.debtor, share.amount
        FROM split 
        LEFT JOIN share 
        ON split.share = share.id
        WHERE debtor = 6 OR creditor = 6 
    ) As split
    LEFT JOIN (
        SELECT split.share, SUM(weight) AS sum
        FROM split
        GROUP BY split.share
    ) wsum
    ON split.share = wsum.share;
    

    或更正确地书写:

    SELECT split.share, split.weight, split.creditor, split.debtor, share.amount, wsum.sum
    FROM split 
    LEFT JOIN share 
    ON split.share = share.id 
    LEFT JOIN (
        SELECT split.share, SUM(weight) AS sum
        FROM split
        GROUP BY split.share
    ) wsum
    ON split.share = wsum.share
    WHERE split.debtor = 6 OR split.reditor = 6;