如何获取当前列值,上一列值

时间:2009-06-24 04:33:21

标签: sql-server ms-access sql-server-2000

如何获取上一列值?

IIf id1 = id2 then display previous column id1 value


id1  id2

1001 1001
1002 1002 
1003 1003

等......

select id1, id2, Iff id2 = id1 then disply previous id1 value as  idadjusted

输出

id1 id2 id3(Expected)

1001    1001    **1000**
1002    1002    **1001**
1003    1003    **1002**

等......

我想显示id1的前一列值

我的查询

SELECT CARDNO, NAME, TITLENAME, CARDEVENTDATE, MIN(CARDEVENTTIME) AS INTIME, MAX(CARDEVENTTIME) AS OUTTIME, 

CARDEVENTDATE AS LASTDATE, MAX(CARDEVENTTIME) AS LASTTIME

 FROM (SELECT T_PERSON.CARDNO, T_PERSON.NAME, T_TITLE.TITLENAME, T_CARDEVENT.CARDEVENTDATE, T_CARDEVENT.CARDEVENTTIME FROM (T_TITLE INNER JOIN T_PERSON ON T_TITLE.TITLECODE = T_PERSON.TITLECODE) INNER JOIN T_CARDEVENT ON T_PERSON.PERSONID = T_CARDEVENT.PERSONID ORDER BY T_PERSON.TITLECODE) GROUP BY CARDNO, NAME, TITLENAME, CARDEVENTDATE

对于LastDate - 我想显示上一列cardeventdate值 对于Lasttime - 我想显示上一个列的停机时间值

需要查询帮助?

3 个答案:

答案 0 :(得分:1)

on子句用于检索以前的id,我已经测试过并且工作正常。 即使中间ID缺失,即ids不连续,该解决方案仍然有效

select t1.id, t1.column1, t1.column2,
case 
    when (t1.column1 = t1.column2) then t2.column1
    else null
end as column3
from mytable t1
left outer join mytable t2 
    on t1.id = (select max(id) from mytable where id < t1.id)

对于复杂查询,您可以创建一个视图,然后将以上sql格式用于您的视图:

创建视图MyView:

SELECT CARDNO, NAME, TITLENAME, CARDEVENTDATE, MIN(CARDEVENTTIME) AS INTIME, MAX(CARDEVENTTIME) AS OUTTIME 
    FROM (SELECT T_PERSON.CARDNO, T_PERSON.NAME, T_TITLE.TITLENAME, T_CARDEVENT.CARDEVENTDATE, T_CARDEVENT.CARDEVENTTIME 
        FROM T_TITLE
            INNER JOIN T_PERSON ON T_TITLE.TITLECODE = T_PERSON.TITLECODE 
            INNER JOIN T_CARDEVENT ON T_PERSON.PERSONID = T_CARDEVENT.PERSONID 
            ORDER BY T_PERSON.TITLECODE) GROUP BY CARDNO, NAME, TITLENAME, CARDEVENTDATE

然后查询将是:

select  v1.CARDNO, v1.NAME, v1.TITLENAME, v1.CARDEVENTDATE, v1.INTIME, v1.OUTTIME,
    case
        when (v1.NAME = v1.TITLENAME) then  v2.CARDEVENTDATE -- Replace v1.NAME = v1.TITLENAME with your reqd condn
        else null end as LASTDATE,
    case
        when (v1.NAME = v1.TITLENAME) then v2.OUTTIME -- Replace v1.NAME = v1.TITLENAME with your reqd condn
        else null end as LASTTIME
from myview v1
    left outer join myview v2 
        on v2.CARDNO = (select max(CARDNO) from table1 where CARDNO < v1.CARDNO)

如果需要使用适当的condn替换stmt,则v1.NAME = v1.TITLENAME。我不确定这个问题中没有提到的condn。

答案 1 :(得分:0)

在设计数据库时,您应该考虑以下事实:您不能依赖正确顺序的所有行。相反,您应该创建一个标识值,每个新行增加1。如果你这样做,你的解决方案变得容易(或至少更容易)

假设一个名为ID的新列

SELECT colum1 FROM myTable WHERE ID = (SELECT ID FROM myTAble WHERE Column1 = Column2) - 1

如果你没有匹配,你将得到ID -1,这不存在,所以你没事。

如果可以获得多个匹配,您也必须考虑

答案 2 :(得分:0)

您的牌桌不在first normal form(1NF):

根据Date对1NF的定义, 当且仅当表格为1NF时,表格为1NF “与某种关系同构”,其中 具体而言,它意味着它满足 以下五个条件:

1)行没有从上到下的排序。

2)列没有从左到右的排序。

3)...