这适用于您以前的数据。当另一组 的平均值相同时,就会出现问题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 |