I have a query to return various figures from a combination of tables. I am using jooq to run this query.
final SiteSalesFigures siteSalesFigures =
dsl.select(
countDistinct(LINE.TRANSACTION_ID).as("transactionCount"),
sum(LINE.PROFIT).as("totalProfit"),
sum(LINE.TOTAL).as("totalSalesAmount"),
sum(LINE.QUANTITY).as("totalItemsSold"),
sum(LINE.PROFIT).divide(sum(LINE.TOTAL)).multiply(100).as("profitMarginPercentage"),
avg(TRANSACTIONS.NO_OF_ITEMS).as("averageItemsPerTransaction"),
sum(LINE.TOTAL).divide(countDistinct(LINE.TRANSACTION_ID)).as("averageSalesTotalPerTransaction"),
sum(LINE.PROFIT).divide(countDistinct(LINE.TRANSACTION_ID)).as("averageProfitTotalPerTransaction"))
.from(TRANSACTIONS)
.join(LINE).on(TRANSACTIONS.TRANSACTION_ID.equal(LINE.TRANSACTION_ID))
.leftJoin(ITEM).on(LINE.ITEM_ID.equal(ITEM.ITEM_CODE))
.where(TRANSACTIONS.SITE_ID.equal(siteId))
.and(TRANSACTIONS.NO_OF_LINES.greaterThan(0))
.and(TRANSACTIONS.START_TIME
.between(new Timestamp(reportStartDate.toInstant().toEpochMilli()))
.and(new Timestamp(reportEndDate.toInstant().toEpochMilli())))
.and(TRANSACTIONS.TRANSACTION_TYPE_ID.notEqual(cancelledSaleID))
.fetchOneInto(SiteSalesFigures.class);
The averageItemsPerTransaction is proving to be the issue. I completely understand why it doesn't work, but I'm not sure how I can make it work. Unfortunately the join is necessary due to exclusions which make use of the Line table.
If a transaction has 3 lines, then the transaction details (which includes no_of_items) get replicated three times, which is resulting in incorrect values.
I know the correct values as I have ran the average(no_of_items) query on just the transactions table.
Here is what the table looks like for just two transactions (hiding columns not needed for this example):
**transaction_id** **no_of_lines no_of_items**
8abf1720-51f6-a1bf-4714-004b644cb99f --- 2 --- 2
8abf1720-51f6-a1bf-4714-004b644cb99f --- 2 --- 2
d239feab-38ea-7c8a-4814-7d5a38f74949 --- 3 --- 4
d239feab-38ea-7c8a-4814-7d5a38f74949 --- 3 --- 4
d239feab-38ea-7c8a-4814-7d5a38f74949 --- 3 --- 4
You'll notice the number of lines doesn't always equal the number of items (a line can have one item scanned twice for example)
Does anybody have a solution?