1

顧客の注文の最後の支払いを日付の降順で一覧表示したいと思います。

私はSQLクエリを書きました

 SELECT CARHARTAR,
       CARHARREFNO,
       CARHARCARKOD,
       CARHARCARUNVAN,
       CARHARACIKLAMA,
       CARHARTUTAR
FROM   CARHAR
WHERE  ( CARHARTIPI IN ( 2, 4 ) )
       AND ( CARHARISTIPNO IN ( 2, 6 ) )
       AND ( CARHARCARKOD NOT LIKE 'W%' )
       AND ( CARHARCARKOD NOT LIKE 'Z%' )
       AND ( CARHARGCFLAG = 2 )
       AND ( CARHARIADEFLAG = 0 )
ORDER  BY CARHARTAR DESC 

このクエリは、日付の降順ですべての支払い順序を一覧表示します。しかし、私は最後の支払いだけが必要です。group by carharcarkodを使用していますが、集計関数に問題があります。私は何をすべきか ?

これがクエリ結果のスクリーンショットです

4

3 に答える 3

1

I think the ROW_NUMBER function would do what you are after:

;WITH Payments AS
(   SELECT  CARHARTAR,
            CARHARREFNO,
            CARHARCARKOD,
            CARHARCARUNVAN,
            CARHARACIKLAMA,
            CARHARTUTAR,
            ROW_NUMBER() OVER(PARTITION BY CARHARCARKOD ORDER BY CARHARTAR DESC) [RowNumber]
    FROM    CARHAR
    WHERE   CARHARTIPI IN (2, 4)
    AND     CARHARISTIPNO IN (2, 6)
    AND     CARHARCARKOD NOT LIKE 'W%'
    AND     CARHARCARKOD NOT LIKE 'Z%'
    AND     CARHARGCFLAG = 2
    AND     CARHARIADEFLAG = 0
)
SELECT  CARHARTAR,
        CARHARREFNO,
        CARHARCARKOD,
        CARHARCARUNVAN,
        CARHARACIKLAMA,
        CARHARTUTAR
FROM    Payments
WHERE   RowNumber = 1
ORDER BY CARHARTAR 
于 2012-07-16T13:37:47.400 に答える
0

group by句を使用する場合は、選択するgroupにすべてのフィールドを含める必要があります。

SELECT CARHARTAR,
   CARHARCARKOD FROM   CARHAR WHERE  ( CARHARTIPI IN ( 2, 4 ) )
   AND ( CARHARISTIPNO IN ( 2, 6 ) )
   AND ( CARHARCARKOD NOT LIKE 'W%' )
   AND ( CARHARCARKOD NOT LIKE 'Z%' )
   AND ( CARHARGCFLAG = 2 )
   AND ( CARHARIADEFLAG = 0 ) GROUP BY CARHARTAR,carharcarkod DESC 
于 2012-07-16T12:49:09.920 に答える
0
with cte as(
SELECT CARHARCARKOD,max(CARHARTAR) [CARHARTAR]
FROM   CARHAR
WHERE  ( CARHARTIPI IN ( 2, 4 ) )
       AND ( CARHARISTIPNO IN ( 2, 6 ) )
       AND ( CARHARCARKOD NOT LIKE 'W%' )
       AND ( CARHARCARKOD NOT LIKE 'Z%' )
       AND ( CARHARGCFLAG = 2 )
       AND ( CARHARIADEFLAG = 0 )
group by CARHARCARKOD    )   
select C.CARHARTAR,
       C.CARHARREFNO,
       C.CARHARCARKOD,
       C.CARHARCARUNVAN,
       C.CARHARACIKLAMA,
       C.CARHARTUTAR
FROM  cte join CARHAR C
on  CTE.CARHARCARKOD =C.CARHARCARKOD     
and cte.CARHARTAR= C.CARHARTAR
于 2012-07-16T12:49:54.010 に答える