我需要为每个company_name和node_name获取表T_TBL_DATA中的第一个文本(具有最低row_id的行)。类似的东西:
SELECT company_name, node_name, [text]
FROM T_TBL_DATA
GROUP BY company_name, node_name
WHERE the selected [text] is from the row with the smallest row_id within each group
有什么想法吗?
答案 0 :(得分:1)
select company_id, node_id, [text]
from t_tbl_data
where row_id in
(
select min(row_id)
from t_tbl_data
group by company_id, node_id
)
答案 1 :(得分:0)
假设id是唯一的。 数据库无关的解决方案在某种程度上:
select
company_id, node_id, (select txt from T_TBL_DATA t2 where t2.id = min(t1.id))
from T_TBL_DATA t1
group by company_id, node_id
对于MS SQL Server 2005及更高版本更简单一点:
-- =============
-- sample data
-- =============
declare @t table
(
id int,
company_id int,
node_id int,
txt varchar(50)
)
insert into @t values (1, 1, 1, 'abc1')
insert into @t values (2, 1, 1, 'abc2')
insert into @t values (3, 1, 2, 'abc3')
insert into @t values (4, 1, 2, 'abc4')
insert into @t values (5, 2, 1, 'abc5')
insert into @t values (6, 2, 1, 'abc6')
insert into @t values (7, 2, 2, 'abc7')
insert into @t values (8, 2, 2, 'abc8')
-- =============
-- solution
-- =============
select
company_id, node_id, txt
from
(
select
*,
id2 = min(id) over(partition by company_id, node_id)
from @t
) t
where id = id2