SELECT
AL1.ACCOUNTING_PERIOD,
AL1.BUSINESS_AREA,
AL1.SAP_ACCOUNT,
AL1.ID,
AL1.USD_AMT,
AL1.BAN_NBR,
AL2.CUST_NBR,
AL2.CUST_NAME
FROM
DSL_AIM.AIM AL1,
DSL_AML.AID AL2
WHERE
(
(
AL1.ACCOUNTING_PERIOD_CD IN ( '2023-02' )
GROUP BY
AL1.ACCOUNTING_PERIOD,
AL1.BUSINESS_AREA,
AL1.SAP_ACCOUNT,
AL1.ID,
AL1.USD_AMT,
AL1.BAN_NBR,
AL2.CUST_NBR,
AL2.CUST_NAME
HAVING
COUNT(*) = 1;
I get a different amount of line items when I have the having statement and when I don’t, so what does HAVING COUNT(*) = 1
mean/do in this context?
2
Answers
It returns all the rows where there is not a duplicate with the same values.
For example, given the sample data:
Then the similar query:
Outputs:
The
2, 2, 2
row is not included as there are two instances of the row and soCOUNT(*) = 2
and not1
for that group; the other rows are included as they are all unique.fiddle
Query seems to be wrong altogether; there’s no join between tables so you’re producing Cartesian product, and then filter it on accounting period. Besides,
where
clause doesn’t require parenthesis, and you have two of them here:where ((
which aren’t closed.you’d see number of rows that share the same set of values in all non-aggregated columns (i.e. all columns specified in
GROUP BY
clause).Then, you can add the
HAVING
clause to further filter result set. In your case, it ishaving count(*) = 1
, which means that there’s only one row per combination.It could have been e.g.
having count(*) > 1
, which means that you’d fetch rows that represent "duplicates".