如何使用SQL查询获取备用行?

时间:2015-09-25 07:10:43

标签: sql sql-server-2014

我有一个要求,我需要产生交替返回1和0的结果。

SELECT * 
FROM 
    (SELECT
         id
         ,itemNo
         ,convert(int,tStationsType_id) as tStationsType_id
         ,tSpecSetpoint_descriptions_id
         ,SetpointValue
         ,rowEvenOdd 
     FROM 
         TEST S
     INNER JOIN
         (SELECT 
              itemNo AS IM, tStationsType_id as ST,
              ROW_NUMBER() OVER(PARTITION  BY itemNo ORDER BY itemNo) % 2 AS rowEvenOdd
          FROM TEST
          GROUP BY itemNo, tStationsType_id) A ON S.itemNo = A.IM
                                               AND S.tStationsType_id = A.ST) t
WHERE
    itemno = '1000911752202'
ORDER BY 
    tStationsType_id

我得到的结果如下所示。

我想在rowEvenOdd中生成替代1和0。但是我注意到,如果我按tStationsType_id订购,我就无法将其替换。

所以基本上,我想要的是什么时候

  • StationsType_id = 2,然后rowEvenOdd = 0
  • StationsType_id = 3,然后rowEvenOdd = 1
  • StationsType_id = 6,然后rowEvenOdd = 0
  • StationsType_id = 8,然后rowEvenOdd = 1
  • StationsType_id = 10,然后rowEvenOdd = 0

enter image description here

有人可以帮我解决这个问题吗?

感谢。

3 个答案:

答案 0 :(得分:1)

如果您只需要在结果集中交替使用0和1,请使用SEQUENCE,如下所示:

CREATE SEQUENCE EvenOdd
   START WITH 0
   INCREMENT BY 1
   MAXVALUE 1
   MINVALUE 0
   CYCLE;
GO
SELECT SalesId, NEXT VALUE FOR EvenOdd as EvenOddColumn FROM Sales
DROP SEQUENCE EvenOdd

要了解详情,请转到此处的序列的MSDN页面:https://msdn.microsoft.com/en-us/library/ff878091.aspx

答案 1 :(得分:0)

您可以使用case when then

SELECT 

case
     when exists (SELECT 1 FROM  StationsTypeMaster 
      M WHERE  M.StationsType_id=A.StationsType_id)
     then 1
     else 0 end as rowEvenOdd 

,*
 FROM 
 (
 select id

  ,itemNo
  ,convert(int,tStationsType_id) as tStationsType_id
  ,tSpecSetpoint_descriptions_id
  ,SetpointValue
,rowEvenOdd from TEST S
inner join 
(select itemNo AS IM,tStationsType_id as ST,
ROW_NUMBER() OVER(PARTITION  BY itemNo ORDER BY itemNo)%2 AS rowEvenOdd
from TEST
group by itemNo,tStationsType_id

)A

on S.itemNo = A.IM
and S.tStationsType_id = A.ST) t
where itemno = '1000911752202'
order by tStationsType_id

答案 2 :(得分:0)

使用DENSE_RANK代替ROW_NUMBER:

SELECT * FROM 
(  
  SELECT
    id,
    itemNo
    convert(int,tStationsType_id) as tStationsType_id,
    tSpecSetpoint_descriptions_id,
    SetpointValue,
    (DENSE_RANK() OVER(ORDER BY CAST(A.ST as INT)) - 1)%2 AS rowEvenOdd
  FROM
  TEST S
  JOIN
  (
    SELECT
      itemNo AS IM,
      tStationsType_id as ST
    FROM 
      TEST
    GROUP BY
      itemNo,tStationsType_id
    )A
  ON 
    S.itemNo = A.IM
    and S.tStationsType_id = A.ST
) t
WHERE
  itemno = '1000911752202'
ORDER BY
  tStationsType_id