如何用单条ABAP SELECT语句筛选BSID表中重复的BUKRS-KUNNR-DMBTR组合
Yep, you absolutely can pull this off with one SELECT statement—your original query was just tripping up on where to place the aggregate filter. Let’s fix that right away.
The Working Query
The key mistake in your initial code was using WHERE to filter the COUNT(*) result. Aggregate conditions like this belong in the HAVING clause: WHERE filters individual rows before grouping happens, while HAVING filters the grouped results after aggregation is done.
Here’s the corrected version:
SELECT bukrs kunnr dmbtr COUNT(*) INTO TABLE git_double FROM bsid WHERE bukrs = '1000' AND blart = 'WP' AND budat IN s_budat AND gjahr IN s_gjahr GROUP BY bukrs kunnr dmbtr HAVING COUNT(*) > 1.
What This Does Step-by-Step
- The
WHEREclause first narrows down BSID records to only those matching your core criteria (company code 1000, document type WP, date ranges, etc.). - It then groups the remaining records by the three fields you care about:
BUKRS,KUNNR,DMBTR. - Finally, the
HAVINGclause keeps only those groups where the combination appears more than once, along with the count of duplicates for each group.
If You Need Full Duplicate Rows (Not Just Grouped Summaries)
If your goal is to pull every individual record that’s part of a duplicate combination (instead of just the grouped count), you can nest the grouping logic in a subquery:
SELECT bukrs kunnr dmbtr INTO TABLE git_double FROM bsid WHERE bukrs = '1000' AND blart = 'WP' AND budat IN s_budat AND gjahr IN s_gjahr AND (bukrs, kunnr, dmbtr) IN ( SELECT bukrs kunnr dmbtr FROM bsid WHERE bukrs = '1000' AND blart = 'WP' AND budat IN s_budat AND gjahr IN s_gjahr GROUP BY bukrs kunnr dmbtr HAVING COUNT(*) > 1 ).
This will return every row from BSID that belongs to a repeating (BUKRS, KUNNR, DMBTR) set.
内容的提问来源于stack exchange,提问作者ekekakos

