sql - Group related records, but pick certain fields from only the first record -


I am starting a composite function on more than one record, which is grouped by common id The problem is, I also want to export some other areas which may be different from grouped records, but I want to get some of those fields from a record (first one, according to the order of the query).

Example of starting point:

  Select customer_ id, amount (serial number), date_created by group customer_id by referral_code order  

Check the referral code, but excluding an integrated function means that I must also group according to that field, and it is not what I want - in this example I need a line per customer. Referred Referral Code Only By First Order I care about and I'm happy to throw referral codes later.

This is in PostgreSQL, but perhaps the syntax from other DBs can be very similar.

Rejected solution:

  • Maximum () or min () can not be used because command is important.
  • A subquery may already work, but does not scale; This is a very small example. My actual query has dozens of fields such as referrals, which only make me the first example, and dozens of WHERE clauses, which are duplicated in a subquarium, will create a maintenance nightmare.

OK, it's really quite easy.

First of all, write a query that will aggregate:

select customer_id, sum (order_total) from the order group, now type a query Which will return 1 referral_ code and date_created for the given Customer ID:

  Customer_ID, date_created, different order on customer_id from order order customer_id, date_created  

Now, you can now join just choosing 2:

 Select from  x1.customer_id, x1.sum, x2.date_created, x2.referral_code (select customer_id, sum (sum_total) Customer_id By the order group (as inclusion in x1) by X2.date_created  

using the command (customer_id) in the form of X2 (customer_id) by customer_id, date_Created, customer_id Order order by order_created; There may be typo in it, but generally it should work.


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -