开发者

Remove column in UNION resultset, based on SUM of column values

I have written a query which I paraphrase at the bottom of this question. It correctly gets a total score for a number of questions asked of people. So, resultsets looks like this:

            | David |  Bill  | Mary | James
Question 1  |   10  |   10   |  0   |   0
Question 2  |   10  |   20   |  0   |   0
Question 3  |   10  |   30   |  0   |   0
Question 4  |   0   |   20   |  0   |   1

What I need to do, and can't figure out, is how to remove any people from the resultset where they have zero marks for all of the questions asked. So, 'Mary' would be removed from the results above, leaving:

            | David |  Bill  | James
Question 1  |   10  |   10   |   0
Question 2  |   10  |   20   |   0
Question 3  |   10  |   30   |   0
Question 4  |   0   |   20   |   1

Here is the query which needs further developing:

SELECT
    `questions`,
    SUM(`0`) AS `David`,
    SUM(`1`) AS `Bill`
FROM(
(SELECT
    ROUND(((SUM(`sm`.`ScorecardMark`) * `sc`.`ScoreCriteriaWeight`)/(COUNT(`sm`.`ScorecardMark`) * `sc`.`ScoreCriteriaWeight`))*100) AS `0`,
    0 AS `1`
FROM
    `tables`
WHERE
    `clauses`
GROUP BY
    `questions`)
UNION
(SELECT
    0 AS `0`,
    ROUND(((SUM(`sm`.`ScorecardMark`) * `sc`.`ScoreCriteriaWeight`)/(COUNT(`sm`.`ScorecardMark`) * `sc`.`ScoreCriteriaWeight`))*100) AS `1`
FROM
    `tables`
WHERE
    `clauses`
GROUP BY
    `questions`)
)  AS `tbltotals`
GROUP 开发者_开发问答BY
    `questions`


I think a better approach would be to select questions as columns, as it should be easier to get the list of needed questions than getting a list of people who scored better than 0.

Then you can apply normal row-level filtering on people. And you can transpose the result to switch rows and columns in you application's code, in case you need that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜