Sql 如何仅在第一列上返回distinct,而仍然返回其他4列

Sql 如何仅在第一列上返回distinct,而仍然返回其他4列,sql,sql-server-2008,Sql,Sql Server 2008,下面是我正在尝试使用的sql查询 SELECT distinct r.Heat ,c.ctemp ,s.ShiftIdent ,r.ChargeSeq ,s.rollLocSeq FROM (NYS1ShiftCut s inner join NYS1CharpyOrders c on c.CharpyOrderID = s.CharpyID) join NYS1Reheat r on r.LocSeq = s.RollLocSeq where c.CTemp < +40 order

下面是我正在尝试使用的sql查询

SELECT distinct
r.Heat
,c.ctemp
,s.ShiftIdent
,r.ChargeSeq
,s.rollLocSeq
FROM (NYS1ShiftCut s inner join NYS1CharpyOrders c on c.CharpyOrderID = s.CharpyID)
join NYS1Reheat r on r.LocSeq = s.RollLocSeq 
where c.CTemp < +40 
order by s.rollLocSeq desc

SQL Server中没有为非分组列提供任意值的构造。您需要按照这些列进行分组,或者使用一些聚合函数

如果其他列的值与您在注释中指出的值无关,则可以使用MIN为每列选择一个值:

SELECT distinct
r.Heat
,MIN(c.ctemp)
,MIN(s.ShiftIdent)
,MIN(r.ChargeSeq)
,MIN(s.rollLocSeq)
FROM (NYS1ShiftCut s inner join NYS1CharpyOrders c on c.CharpyOrderID = s.CharpyID)
join NYS1Reheat r on r.LocSeq = s.RollLocSeq 
where c.CTemp < +40 
GROUP BY r.Heat
order by s.rollLocSeq desc

最小值的选择是任意的,is也可以是MAX或AVG,但要注意的是,AVG可能会给出源数据中不存在的值,如果它们不都相等。

如果对于相同的r.Heat值,其他三个值不同怎么办?您想要哪些值?最大值?敏?平均的随机挑选一个?这是一个小样本的返回信息,因为它现在是。。。439799-04 05/22/15154D 126 542949330 439799-04 05/22/15154D 124 542949310 439799-04 05/22/15154D 123 542949300 439799-04 05/22/15154D 122 542949290 439799-04 05/22/15154D 121 542949280 43999-04 05/22/15154D 120 542949270 439799-04 05/22/15154D 119 542949260 439799-04 05/22/22/15154D 118 542949250 439977-04 05/22/15154240 117439797-04 05/22/15154D 116 542949230所有其他项目都是必需的,但与排序顺序无关。@模糊-给定示例的预期输出是什么。我已尝试分组,但仍会出现错误,可能是一个小示例?分组方式不起作用。我已经编辑了上面的查询。请检查。我发现这是我的应用程序的最佳结果。我在想,通过使用MIN,它会给我错误的、太少的回报,然后意识到这正是我想要的。谢谢斯坦利博士的回答。
How about Something like the following:
SELECT
r.Heat
,c.ctemp
,s.ShiftIdent
,r.ChargeSeq
,s.rollLocSeq
FROM (NYS1ShiftCut s inner join NYS1CharpyOrders c on c.CharpyOrderID = s.CharpyID)
join NYS1Reheat r on r.LocSeq = s.RollLocSeq 
where c.CTemp < +40 
AND r.heat IN (SELECT DISTINCT r.HEAT FROM NYS1ShiftCut s inner join NYS1CharpyOrders c on c.CharpyOrderID = s.CharpyID)
join NYS1Reheat r on r.LocSeq = s.RollLocSeq) 
order by s.rollLocSeq desc
SELECT distinct
r.Heat
,MIN(c.ctemp)
,MIN(s.ShiftIdent)
,MIN(r.ChargeSeq)
,MIN(s.rollLocSeq)
FROM (NYS1ShiftCut s inner join NYS1CharpyOrders c on c.CharpyOrderID = s.CharpyID)
join NYS1Reheat r on r.LocSeq = s.RollLocSeq 
where c.CTemp < +40 
GROUP BY r.Heat
order by s.rollLocSeq desc