SQL Select和Group By子句

时间:2015-09-02 14:48:59

标签: sql sql-server

我有根据下表的数据,我传入一个数字列表,需要raceId所有数字出现在该种族的数据列中。

+-----+--------+------+
| Id  | raceId | data |
+-----+--------+------+
|  14 |      1 |    1 |
|  12 |      1 |    2 |
|  13 |      1 |    3 |
|  16 |      1 |    8 |
|  47 |      2 |    1 |
|  43 |      2 |    2 |
|  46 |      2 |    6 |
|  40 |      2 |    7 |
|  42 |      2 |    8 |
|  68 |      3 |    3 |
|  69 |      3 |    6 |
|  65 |      3 |    7 |
|  90 |      4 |    1 |
|  89 |      4 |    2 |
|  95 |      4 |    6 |
|  92 |      4 |    7 |
|  93 |      4 |    8 |
| 114 |      5 |    1 |
| 116 |      5 |    2 |
| 117 |      5 |    3 |
| 118 |      5 |    8 |
| 138 |      6 |    2 |
| 139 |      6 |    6 |
| 140 |      6 |    7 |
| 137 |      6 |    8 |
+-----+--------+------+

示例我传入1,2,7我会得到以下ID:

2 and 4

我尝试过简单的陈述

SELECT * FROM表WHERE((data = 1)或(data = 2)或(data = 7))

但我真的不明白分组依据或者确实是否正确的方法。

3 个答案:

答案 0 :(得分:1)

select raceId
from yourtable
where data in (1,2,7)
group by raceId
having count(raceId) = 3 /* length(1,2,7) */

这是假设raceId,数据对是唯一的。如果不是你应该使用

select raceId
from (select distinct raceId, data
      from yourtable
      where data in(1,2,7))
group by raceId
having count(raceId) = 3

答案 1 :(得分:0)

SELECT DISTINCT raceId WHERE data IN (1, 2, 7)

答案 2 :(得分:0)

这是“set-within-sets”查询的示例。我想通过group byhaving来解决这些问题。

select raceid
from races
where data in (1, 2, 7)
group by raceid
having count(*) = 3;