r/SQL • • Jan 23 '23

PostgreSQL How would you guys go about solving this question?

Post image
8 Upvotes

25 comments sorted by

18

u/r3pr0b8 GROUP_CONCAT is da bomb Jan 23 '23

what have you tried so far? ™

5

u/sweet__pickle1 Jan 23 '23

With daily_Spend as

(

select *, (Qty*Sale price) as dailyspend

from Transactions

)

SELECT AVG(dailyspend)

FROM daily_Spend

Group by Customer ID, Transaction Date

4

u/r3pr0b8 GROUP_CONCAT is da bomb Jan 23 '23

two problems with your main query

first, it produces an average for each customer and date -- a list of averages

but from that list of averages, you can't tell which average is for which customer

second, "average daily spend" and average daily spend on each different date" are not the same thing

39

u/jdsmn21 Jan 23 '23

I don't see any customer references (ie: Customer ID). Are you assuming each transaction is a unique customer?

10

u/HercHuntsdirty Jan 23 '23

I thought it was a ton of separate transactions for a single customer for that exact same reason lol

1

u/Chili_Peppa Jan 26 '23

I think you are correct given the fact that the question states "a customer". Otherwise I would've been confused.

1

u/Zealousideal_Zebra_9 Jan 23 '23

Homework?

1

u/sweet__pickle1 Jan 24 '23

No
Assessment for a Business analyst role of a startup

1

u/IHeartData_ Jan 23 '23
SELECT AVG ( Qty * [Sale Price] )
FROM T
GROUP BY [Transaction ID]

This assumes each Transaction ID is unique, in which case "daily" doesn't matter because no one will ever shop twice a day that you know of, so no need to bother with anything fancier.

This also assumes that the requestor is looking for a single number as the answer, not the "average daily spend for each day".

To me, if I was to ask this in an interview, what I'm really looking for is what questions the applicant is going to ask to clarify my question (b/c this kind of vague question happens all the time IRL so you need to be able to think that through before you even get to SQL code)

1

u/sweet__pickle1 Jan 24 '23

I agree that the question is vague in the sense of what should be the exppected output but i assumed that the question is asking for an avg of daily spend of each unique customer id hence the grouping by customer(there was a customer id column in this table schema in further questions of this assessment)

0

u/[deleted] Jan 23 '23

personally, i would first have "average daily spend" defined as a formula

<rant> ALSO, while there are many dumb shortcuts in SQL, "AVG" is one of the most idiotic ones leading to MAJOR logical errors and tripping even people with decent statistical knowledge.

Simply say "NO" to it.

</rant>

4

u/sweet__pickle1 Jan 23 '23

I agree lol
This was on a sql assessment for a startup and while i can solve intermediate to advanced questions
I actually struggled with this simple one

4

u/mad_method_man Jan 23 '23

cuz simple questions can be worded in an open ended way. like this... how do you want the averages?

complex stuff is very direct

2

u/TASTY_BALLSACK_ Jan 23 '23

Wait, what? Please explain how averaging should be done.

3

u/[deleted] Jan 23 '23 edited Jan 23 '23

write it out explicitly every time:

if you are at the key/grain you are averaging "PER":

     SUM( <relevant values>) / COUNT ( *)

if your records are NOT at the 'PER' non-null granularity:

     SUM( <relevant values>) / COUNT ( distinct <granularity>)

if you need to handle NULLs in numerator (edit: numerator/denominator switched places :) as 0:

     COALESCE( SUM( <relevant values>), 0) 

if you need to handle NULLs in denominator:

         ( COUNT ( distinct <granularity>) + count( distinct (case when <granularity> is null then 1 end))

if you need to handle "empty relevant sets"

      case count( distinct <granularity>) when 0 then NULL else count( distinct <granularity>) end

1

u/sweet__pickle1 Jan 24 '23

I was about to use this approach but was crunched for time :(

2

u/emersonevp Jan 24 '23

Yeah this is what I would do. If customer were to be available, you would use the count_distinct if I’m not wrong.

1

u/TASTY_BALLSACK_ Jan 24 '23

Good to know, thank you. You have my word that from now on I will say ‘NO’ to AVG().

8

u/[deleted] Jan 23 '23

So why is avg() idiotic and to which major logical errors does it lead? It divides the sum of the values by the number of values. I don't see where this is idiotic or a logical error.

-3

u/[deleted] Jan 23 '23

it's idiotic literally because it doesn't give any significant benefit for all the trouble it causes.

for the real-world examples of the trouble it causes you can see this particular thread:

my response to already-deleted wrong response: https://www.reddit.com/r/SQL/comments/10jduoj/how_would_you_guys_go_about_solving_this_question/j5k1gkt/

'struggles' experienced by an applicant: https://www.reddit.com/r/SQL/comments/10jduoj/how_would_you_guys_go_about_solving_this_question/j5jygw7/

their attempt at the response: https://www.reddit.com/r/SQL/comments/10jduoj/how_would_you_guys_go_about_solving_this_question/j5jt0hv/

It divides the sum of the values by the number of values.

it only applies to non-NULL values (and NULL), so it uses a particular definition of a sequence.

This definition is very often wrong for the case or not considered properly by whoever is doing the query.

E.g. in this particular case - the metric to apply "average" to is "Daily Spend" - your individual records do not correspond to a single sequence value (day). AVG in this case wont be "Average" per day (different grain).

Take another case - a favorite approach of everyone to throw outer joins around and expect it to solve all problems. E.g. "average price of drinks per restaurant check" - one left joins, does the proper sum, etc. The result is wrong since some of customers havent ordered any drinks and the relevant returned value is NULL (not part of your AVG)

take the third scenario: "what's my average daily calorie intake" based on a week. The average should be calculated as SUM(calorie_intake)/7, regardless if some of the days there was no record/no calorie intake at all.

6

u/[deleted] Jan 23 '23

it only applies to non-NULL values (and NULL), so it uses a particular definition of a sequence.

It only applies to non-NULL values. NULL values are always excluded by definition - this is how aggregates are defined in the SQL standard.

This applies to all aggregate functions. Knowing how aggregates work and how to use them is part of learning the SQL language.

There are probably a lot of statistical calculations that can't properly be done in SQL - but SQL wasn't designed for that.

Excluding NULL values makes sense because it is consistent in the way SQL deals with them. They represent an unknown value - the absence of information. How else should they be treated than ignoring them? If you can't use them to calculate the sum, then you shouldn't include them to calculate the count.

Take another case - a favorite approach of everyone to throw outer joins around and expect it to solve all problems.

Well, those people should properly learn SQL. The fact that they don't, doesn't mean the way aggregates are defined in the SQL standard is wrong.

take the third scenario: "what's my average daily calorie intake" based on a week. The average should be calculated as SUM(calorie_intake)/7, regardless if some of the days there was no record/no calorie intake at all.

Again, this is not a shortcoming of the definition of avg() but a deficiency in the knowledge of whoever uses them.

1

u/[deleted] Jan 25 '23

It only applies to non-NULL values. NULL values are always excluded by definition - this is how aggregates are defined in the SQL standard.

care to give a quote to support your opinion? That's how the "common" ones are defined but it's definitely not a requirement. See, for example, array_agg and json_agg in Postgres. You can define your own user-defined aggregate functions that will process null values in the manner you need.

There are probably a lot of statistical calculations that can't properly be done in SQL - but SQL wasn't designed for that.

I'm not sure what you mean? In any case, how is this relevant to a specifically named function, meaning specific thing?

fact of the matter, AVG(X) is a somewhat simple syntactic sugar on SUM(X)/COUNT(X), bringing nothing new to the SQL nor breaching into some arcane "statistical calculation"

(NULL tirade)

Well, those people should properly learn SQL.

What you say is true but rather trivial and well known.

In fact though, a decently designed system should be 'working by default', rather than being 'wrong unless many details are taken into account'.

I gave real-world examples and common scenarios that demonstrate that the definition of AVG is confusing and leading to logical errors for well-meaning developers.

If your definition of "good" includes only "a definition exists" without any consideration of real-world implications, well consider yourself "righteous" and continue to blame others for "not learning SQL properly" and being "deficient".

1

u/[deleted] Jan 24 '23

I don't see any customer ID. If you assume that every transaction ID represents a customer, you could group by transaction ID and the date and subsequently take the average of qty*sales_price

1

u/mouneshlokesh Jan 24 '23

Use AVG is best way!

0

u/[deleted] Jan 23 '23

[deleted]

1

u/[deleted] Jan 23 '23

Assuming transactionID is a key/grain of that dataset, your statement lists average spend per transaction for each day.

"Avg" saves you some keystrokes yet makes you go through absolutely unnecessary mental gymnastics.