SQL Server中的分组依据,表中有一个值
我有一个包含以下数据的表,并尝试按分组,但没有得到我想要的数据SQL Server中的分组依据,表中有一个值,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个包含以下数据的表,并尝试按分组,但没有得到我想要的数据 create table #test ( id int, value int, code int, info varchar(20) ) insert into #test values (1234, 7666, 1, '1stfail'), (1234, 7665, 2, '2ndfail'), (1234, 7664, 3, '3rdfail')
create table #test
(
id int,
value int,
code int,
info varchar(20)
)
insert into #test
values (1234, 7666, 1, '1stfail'),
(1234, 7665, 2, '2ndfail'),
(1234, 7664, 3, '3rdfail'),
(2434, 8777, 1, '1stfail')
select id, value, code, min(info)
from #test
我得到的结果如下
我想要这样的结果
您需要使用滞后来实现这一点。LAG前进到下一行以获取列的值
select
case when idNew = id then null else id end idCol,
value, code, info
from (
SELECT id, LAG(id) OVER(Order by id) idNew, code, value, info from #test
) as t
您可以使用CASE并仅在row_number等于1时输出ID
SELECT CASE
WHEN row_number() OVER (PARTITION BY id
ORDER BY code) = 1 THEN
id
END id,
value,
code,
info
FROM #test;
您需要将id与每个组的最大值进行比较的条件:
select
case
when value = (select max(value) from #test where id = t.id) then t.id
else null
end as id,
value,
code,
info
from #test as t
order by t.id, t.value desc, t.code
请参阅您应该会收到该代码的错误。。。因为你没有分组。除此之外,数据是相同的,减去您在试图使报表看起来更漂亮时忽略了一些值这一事实。让您的应用程序层为您做到这一点。