开发者

Please Explain how to Express this SQL as a Single Statement using Derived Tables

For my own edification, I'm trying to write this SQL functionality in a single statement without using temporary tables. For the life of me, I can't get the query to work without getting a MySQL "ERROR 1248 (42000): Every derived table must have its own alias."

Here's something akin, albeit broken, to what I want:

SELECT split.share, split.weight, split.creditor, split.debtor, share.amount, wsum.sum
F开发者_如何学PythonROM (
    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;

Here's a working version of what I'm trying to expressed using temporary tables:

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;

Thanks for the help.


Try this:

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;

Or more correctly written:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜