我是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 ...
我该怎么做?
感谢
答案 0 :(得分: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
虽然取决于你的数据库,查询和版本,你可能会得到不可预测/不可靠的回报。
答案 1 :(得分: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()
替换为列。
答案 2 :(得分:0)
如果我理解你的输出,如果你使用的是PostGreSQL 9,你可以使用它:
SELECT chip_id ,
string_agg(sample_id, ' or ')
FROM your_table
GROUP BY chip_id
答案 3 :(得分:0)
您需要使用GROUP BY查询对数据进行分组 分组时,通常需要max,min或其他值来表示您的组。你可以做总结,计数,各种小组操作。
对于您的示例,您似乎不想要特定的组操作,因此查询可以像这样简单:
SELECT chip_id, MAX(sample_id)
FROM table
GROUP BY chip_id
这样您就会检索每个sample_id
的最大chip_id
。