即使在使用distinct之后也无法获得正确的结果

时间:2012-11-23 13:57:26

标签: sql sql-server

我正在尝试获取以下查询的结果:

select distinct
       REQ_ID
     , ID
     , MAX(STEP) as step
     , SUBSTRING(p1.NAME,9, len(p1.NAME)) as _index_
     , p2.value as location

from HISTORY h

LEFT JOIN Parameter p1 
on     p1.WP_ID=h.ID
   AND (   (    p1.NAME like 'name_' 
            AND p1.VALUE like h.ID COLLATE DATABASE_DEFAULT ) 
        OR (    p1.NAME like 'name__' 
            AND p1.VALUE like h.ID COLLATE DATABASE_DEFAULT) )

LEFT JOIN Parameter p2 
on     p2.WP_ID=h.ID 
   AND p2.PA_NAME = 'Location' + (SUBSTRING(p1.NAME,9, len(p1.NAME)) ) 

WHERE h.ROLE = 'rock'

GROUP BY REQ_ID, ID, step, p1.name, p2.value

问题是查询返回了多于1个结果(在我的情况下有6个)并且MAX(STEP)值没有返回最大值,我可以看到像0,1,3,0这样的值, 1,2 有没有办法只获得max(step)的结果? step字段为varchar(1)

3 个答案:

答案 0 :(得分:0)

要只获得一个步骤最高的记录,请使用

SELECT TOP(1)
......
......
ORDER BY step desc

答案 1 :(得分:0)

尝试这种方式(从分组中删除步骤):

select REQ_ID,ID,MAX(STEP) as step,SUBSTRING(p1.NAME,9, len(p1.NAME)) as _index_,
p2.value as location
from HISTORY h
LEFT JOIN Parameter p1 on p1.WP_ID  =h.ID  AND 
( (p1.NAME like 'name_' AND p1.VALUE  like h.ID COLLATE DATABASE_DEFAULT ) 
OR (p1.NAME like 'name__' AND p1.VALUE  like h.ID COLLATE DATABASE_DEFAULT) )
LEFT JOIN Parameter p2 on p2.WP_ID=h.ID AND p2.PA_NAME = 'Location' + (SUBSTRING(p1.NAME,9, len(p1.NAME)) ) 
WHERE h.ROLE = 'rock'
GROUP BY REQ_ID,ID, p1.name, p2.value

删除step并将SUBSTRING(p1.NAME,9, len(p1.NAME))添加到分组依据:

select REQ_ID,ID,MAX(STEP) as step,SUBSTRING(p1.NAME,9, len(p1.NAME)) as _index_,
p2.value as location
from HISTORY h
LEFT JOIN Parameter p1 on p1.WP_ID  =h.ID  AND 
( (p1.NAME like 'name_' AND p1.VALUE  like h.ID COLLATE DATABASE_DEFAULT ) 
OR (p1.NAME like 'name__' AND p1.VALUE  like h.ID COLLATE DATABASE_DEFAULT) )
LEFT JOIN Parameter p2 on p2.WP_ID=h.ID AND p2.PA_NAME = 'Location' + (SUBSTRING(p1.NAME,9, len(p1.NAME)) ) 
WHERE h.ROLE = 'rock'
GROUP BY REQ_ID,ID, SUBSTRING(p1.NAME,9, len(p1.NAME)),p2.value

答案 2 :(得分:0)

在处理first record in a group时,通常最简单的方法是使用ROW_NUMBER()。在不了解您的架构和数据的情况下,我可以说以下查询可以正常工作,但可以进一步简化它......

WITH
  sequenced_data AS
(
  SELECT
    REQ_ID,
    ID,
    ROW_NUMBER() OVER (PARTITION BY req_id, id ORDER BY step DESC) AS sequence_id,
    STEP,
    SUBSTRING(p1.NAME,9, len(p1.NAME)) as _index_,
    p2.value as location
  FROM
    HISTORY    h
  LEFT JOIN
    Parameter  p1
      ON  p1.WP_ID = h.ID
      AND (   (p1.NAME like 'name_' AND p1.VALUE  like h.ID COLLATE DATABASE_DEFAULT ) 
           OR (p1.NAME like 'name__' AND p1.VALUE  like h.ID COLLATE DATABASE_DEFAULT)
          )
  LEFT JOIN
    Parameter  p2
      ON  p2.WP_ID = h.ID
      AND p2.PA_NAME = 'Location' + (SUBSTRING(p1.NAME,9, len(p1.NAME)) ) 
  WHERE
    h.ROLE = 'rock'
  GROUP BY
    REQ_ID,
    ID,
    STEP,
    SUBSTRING(p1.NAME,9, len(p1.NAME)),
    p2.value
)
SELECT
  *
FROM
  sequenced_data
WHERE
  sequence_id = 1

这将为每个req_id, id组合仅提供一行,并始终选择具有最高step值的行。

注意:我不知道是否还需要GROUP BY。我把它留下来只是因为你拥有它。