SQL Server - 突出显示具有特定条件的行序列

时间:2013-09-09 16:01:59

标签: sql sql-server

从我的查询中得到:

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

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

这适用于您之前的数据。如果您对另一组VAL具有相同的平均值,则会出现问题:

SQL Fiddle

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

<强> Results

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

编辑:假设这与问题有关,您可以这样:

SQL Fiddle

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

<强> Results

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