2015-10-06 137 views
1

不同我有這個疑問:SQL - 選擇字段記錄相同的值,在另一

select CPRCOSC, CPRCDCO, FCHPRDT ,CPRDTPA 
from ocsacpr, 
    fasaorl, 
    fasaorh 
where CPRCOSC = 'GHY02' 
    and fclcosc = CPRCOSC 
    and fclcdcm = CPRCDCO 
    and fclverc = CPRVER 
    and fclnumc = CPRNUM 
    and FCHORDN = FCLORDN 
    and FCHCOSC = FCLCOSC 

它給我:

CPRCOSC CPRCDCO  FCHPRDT  CPRDTPA 
GHY02 2015000036 20150728 20150728 
GHY02 2015000037 20150723 20150723 
GHY02 2015000038 20150722 20150722 
GHY02 2015000039 20150918 20150930 
GHY02 2015000040 20150918 20150930 
..... 
GHY02 2015000041 20150731 20150731 
GHY02 2015000041 20150918 20150831 
GHY02 2015000041 20150921 20150930 

在過去的3條記錄(即具有相同CPRCDCO) ,我想只選擇高於FCHPRDT的記錄(在本例中爲20150921)。

如何編輯查詢?

在此先感謝

+7

您可以通過使用表的別名限定所有的列名,並使用顯式'join'語法開始。雖然這不能解決你的問題,但它會讓其他人知道你在做什麼。示例數據和SQL Fiddle也很有用,因爲您實際使用的是數據庫的標籤。 –

回答

1

您可以使用窗口函數(FIRST_VALUE),由CPRCDCO劃分和排序FCHPRDT(降序)來做到這一點。看看功能文檔。

https://msdn.microsoft.com/en-us/library/hh213018.aspx

下面的代碼是要工作得很好,但我建議你也使用INNER JOIN條款,而不是使WHERE子句中的連接。

SELECT DISTINCT 
     CPRCOSC, 
     CPRCDCO, 
     FIRST_VALUE(FCHPRDT) OVER (PARTITION BY CPRCDCO ORDER BY FCHPRDT DESC) AS FCHPRDT, 
     FIRST_VALUE(CPRDTPA) OVER (PARTITION BY CPRCDCO ORDER BY FCHPRDT DESC) AS CPRDTPA 
    FROM 
     OCSACPR, FASAORL, FASAORH 
    WHERE 
     CPRCOSC = 'GHY02' 
     AND FCLCOSC = CPRCOSC 
     AND FCLCDCM = CPRCDCO 
     AND FCLVERC = CPRVER 
     AND FCLNUMC = CPRNUM 
     AND FCHORDN = FCLORDN 
     AND FCHCOSC = FCLCOSC 
+0

它非常適合IBM db2 db!謝謝! – user2075861

0

使用公用表表達式(保存一些輸入)。使用NOT EXISTS返回行,如果沒有其他行具有相同CPRCDCO具有更高FCHPRDT

with cte as 
(
select CPRCOSC, CPRCDCO, FCHPRDT ,CPRDTPA 
from ocsacpr, 
     fasaorl, 
     fasaorh 
where CPRCOSC = 'GHY02' 
    and fclcosc = CPRCOSC 
    and fclcdcm = CPRCDCO 
    and fclverc = CPRVER 
    and fclnumc = CPRNUM 
    and FCHORDN = FCLORDN 
    and FCHCOSC = FCLCOSC 
) 
select * from cte t1 
where not exists (select 1 from cte t2 
        where t2.CPRCDCO = t1.CPRCDCO 
        and t2.FCHPRDT > t1.FCHPRDT) 
相關問題