How to count duplicate rows in a query in efficient way?

走远了吗. 提交于 2020-01-16 18:05:29

问题


I am creating a report in SAP SQ01/SQ02 whose purpose is to show the number of times a product was picked in the specified time frame.

The data is mainly sourced from table LTAP. I just need to be able to count the number of rows Material XYZ is duplicated in and output the number into an extra field and show the value. Also I want this count to happen in a specified time frame, let's say in the last 30 days, this is to make sure it's up to date and relevant.

The below code works, but it's so slow, it takes a couple of seconds to output the count for just 1 material and I need the report to output top 1000 based on the count. Is there a more efficient way to accomplish the same thing?

DATA TAB

DATA : YEAR(4) TYPE N,
       MTH(2) TYPE N,
       DAY(2) TYPE N,
       YEAR1(4) TYPE N,
       MTH1(2) TYPE N,
       DAY1(2) TYPE N,
       FROM_DATE LIKE SY-DATUM,
       count1 like LTAP-UMREZ.
FIELD-SYMBOLS <fs_dtab> TYPE STANDARD TABLE.
DATA: sort_f1 TYPE fieldname.

INITIALIZATION TAB

sort_f1 = 'ltap-matnr'.

Record Processing TAB

YEAR = SY-DATUM(4).
MTH = SY-DATUM+4(2).
DAY = SY-DATUM+6(2).
IF MTH eq 1.
    MTH1 = MTH + 11.
   ELSE.
    MTH1 = MTH - 1.
 ENDIF.
   IF MTH eq 1.
      YEAR1 = YEAR - 1.
        ELSE.
        YEAR1 = YEAR.
   ENDIF.
FROM_DATE(4) = YEAR1.
FROM_DATE+4(2) = MTH1.
FROM_DATE+6(2) = DAY.

END OF SELECTION AFTER TAB

ASSIGN ('%G00[]') TO <fs_dtab>.
IF <fs_dtab> IS ASSIGNED.
  SORT <fs_dtab> BY (sort_f1)
                 DESCENDING.
  DELETE ADJACENT DUPLICATES FROM <fs_dtab>
  COMPARING (sort_f1).
ENDIF.

Extra Field Code

In LTAP, field UMREZ is populated with number "1", so I am using it here to count the duplicates.

clear count.
Select sum( UMREZ ) as UMREZ
  from *LTAP into COUNT
  where *LTAP~MATNR eq LTAP-MATNR
  and *LTAP~QDATU GE from_date.

I expect the report to come out in seconds rather than minutes for a couple of material codes. Alternative code or an improvement to the current one which could accomplish this will be very much appreciated.


回答1:


DATA materials TYPE RANGE OF matnr.

SELECT
    matnr AS material,
    COUNT(*) AS count
  FROM ltap
  INTO TABLE @DATA(result)
  WHERE matnr IN materials
    AND qdatu >= @from_date
  GROUP BY matnr.

Make sure there is an index on the column MATNR. In the current S/4HANA, there is one HW6 that fits, but it deploys on SAP HANA only and may not be available on older releases.



来源:https://stackoverflow.com/questions/55711056/how-to-count-duplicate-rows-in-a-query-in-efficient-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!