admin

选择具有相同值的多行

sql

我有一张表,像这样:

ID  |  Chromosome | Locus | Symbol | Dominance |
===============================================
1   |      10     |   2   |   A    |   Full    |
2   |      10     |   2   |   a    |   Rec.    |
3   |      10     |   3   |   B    |   Full    |
4   |      10     |   3   |   b    |   Rec.    |

我想选择具有相同基因座和染色体的所有行。例如,第3行和第4行。一次可能有2个以上,并且它们可能不是按顺序排列的。

我尝试了这个:

SELECT *
FROM Genes
GROUP BY Locus
HAVING Locus='3' AND Chromosome='10'

但是,即使重复,它总是返回第3行,从不返回第4行。我想我缺少明显而简单的东西,但我茫然。

有人可以帮忙吗?


阅读 151

收藏
2021-05-10

共1个答案

admin

您需要了解,当您GROUP BY在查询中包含内容时,您是在告诉SQL合并行。您将为每个唯一Locus值获得一行。在Having随后过滤这些组。通常,您可以在选择列表中指定aggergate函数,例如:

--show how many of each Locus there is
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus

--only show the groups that have more than one row in them
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus HAVING COUNT(*)>1

--to just display all the rows for your condition, don't use GROUP BY or HAVING
SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10'
2021-05-10