-1

从我的查询中我得到:

----------
| Val  |  Avg |
----------
|  1   |   7  |
----------
|  5   |   7  |
----------
|  2   |   7  |
----------
|  5   |   7  |
----------
|  6   |   7  |
----------
|  5   |   7  |

假设上述内容在某个表“t”中。我想检查是否有三行或更多行的值小于相应的平均值。如果有三个或更多点满足该条件,则应在结果中突出显示它们,如下所示:

----------
|  Val |  Avg | BelowAvg |
----------
|  8   |   7  |     0    |
----------
|  7   |   7  |     0    |
----------
|  9   |   7  |     0    |
----------
|  5   |   7  |     1    |
----------
|  6   |   7  |     1    |
----------
|  5   |   7  |     1    |

有什么建议么?

4

1 回答 1

2

这适用于您以前的数据。当另一组 的平均值相同时,就会出现问题VAL

SQL小提琴

MS SQL Server 2012 架构设置

CREATE TABLE t
    ([Val] int, [Avg] int)
;

INSERT INTO t
    ([Val], [Avg])
VALUES
    (1, 3),
    (5, 3),
    (2, 3),
    (5, 7),
    (6, 7),
    (5, 7)
;

查询 1

SELECT t.*, 
       CASE WHEN t2.cnt >= 3 THEN 1 ELSE 0 END as BelowAvg 
FROM t
LEFT OUTER JOIN (SELECT avg, count(*) as cnt
            FROM t
            WHERE val < avg
            GROUP BY avg) t2 ON t.avg = t2.avg

结果

| VAL | AVG | BELOWAVG |
|-----|-----|----------|
|   1 |   3 |        0 |
|   5 |   3 |        0 |
|   2 |   3 |        0 |
|   5 |   7 |        1 |
|   6 |   7 |        1 |
|   5 |   7 |        1 |

编辑:假设这与一个问题有关,你可以有这样的事情:

SQL小提琴

MS SQL Server 2012 架构设置

CREATE TABLE t
    ([QuestionID] int, [Val] int, [Avg] int)
;

INSERT INTO t
    ([QuestionID], [Val], [Avg])
VALUES
    (1, 1, 3),
    (1, 5, 3),
    (1, 2, 3),
    (2, 5, 7),
    (2, 6, 7),
    (2, 5, 7)
;

查询 1

SELECT t.*, 
       CASE WHEN t2.cnt >= 3 THEN 1 ELSE 0 END as BelowAvg 
FROM t
LEFT OUTER JOIN (SELECT QuestionID, count(*) as cnt
            FROM t
            WHERE val < avg
            GROUP BY QuestionID) t2 ON t.QuestionID = t2.QuestionID

结果

| QUESTIONID | VAL | AVG | BELOWAVG |
|------------|-----|-----|----------|
|          1 |   1 |   3 |        0 |
|          1 |   5 |   3 |        0 |
|          1 |   2 |   3 |        0 |
|          2 |   5 |   7 |        1 |
|          2 |   6 |   7 |        1 |
|          2 |   5 |   7 |        1 |
于 2013-09-09T17:33:32.883 回答