-1

我对 SQL 很陌生,我想做一个SELECT语句来仅检索基于列值的集合的第一行。我将尝试通过一个表格示例使其更清楚。
这是我的表格数据:

chip_id | sample_id
-------------------
1       | 45
1       | 55
1       | 5986
2       | 453
2       | 12
3       | 4567
3       | 9

我想要一个SELECT声明,用这样的方式获取第一行chip_id=1,2,3

chip_id | sample_id
-------------------
1       | 45 or 55 or whatever
2       | 12 or 453 ...
3       | 9 or ...

我怎样才能做到这一点?
谢谢

4

4 回答 4

1

我可能会:

set a variable =0
order your table by chip_id
read the table in row by row
if table[row]>variable, store the table[row] in a result array,increment variable
loop till done
return your result array

尽管取决于您的数据库、查询和版本,您可能会得到不可预测/不可靠的回报。

于 2013-04-03T14:42:31.023 回答
0

您可以使用以下方法获得一个值row_number()

select chip_id, sample_id
from (select chip_id, sample_id,
             row_number() over (partition by chip_id order by rand()) as seqnum
     ) t
where seqnum = 1

这将返回一个随机值。在 SQL 中,表本质上是无序的,因此没有“第一”的概念。您需要一个自动递增的 id 或创建日期或某种定义“第一个”的方式来获得“第一个”。

如果您有这样的列,请替换rand()为该列。

于 2013-04-03T14:12:40.780 回答
0

如果我理解你的输出,如果你使用 PostGreSQL 9,你可以使用这个:

SELECT chip_id , 
       string_agg(sample_id, ' or ')
FROM your_table
GROUP BY chip_id 
于 2013-04-03T14:13:31.950 回答
0

您需要使用GROUP BY查询对数据进行分组。
分组时,通常您希望使用最大值、最小值或其他一些值来代表您的组。您可以进行求和、计数和所有类型的组运算。

对于您的示例,您似乎不需要特定的组操作,因此查询可以像下面这样简单:

SELECT chip_id, MAX(sample_id)
FROM table
GROUP BY chip_id

这样,您将检索sample_id每个chip_id.

于 2013-04-03T14:16:33.280 回答