1

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

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)

4

3 回答 3

0

要仅获得一条最高步长的记录,请使用

SELECT TOP(1)
......
......
ORDER BY step desc
于 2012-11-23T13:59:52.030 回答
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
于 2012-11-23T14:03:36.083 回答
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仍然需要。我把它留在里面只是因为你有它。

于 2012-11-23T14:13:27.507 回答