aggregate-functions

SQL - Select 'n' greatest elements in group

陌路散爱 提交于 2019-12-04 19:01:22
The SQL MAX aggregate function will allow you to select the top element in a group. Is there a way to select the top n elements for each group? For instance, if I had a table of users that held their division rank, and wanted the top two users per division ... Users userId | division | rank 1 | 1 | 1 2 | 1 | 2 3 | 1 | 3 4 | 2 | 3 I would want the query to somehow return users 2,3,4 If it matters, I'm using MySQL. select * from users as t1 where (select count(*) from users as t2 where t1.division = t2.division and t2.rank > t1.rank) <2 order by division,rank SELECT * FROM ( SELECT u1.userid, u1

aggregate of an empty result set

旧街凉风 提交于 2019-12-04 18:19:57
问题 I would like the aggregates of an empty result set to be 0. I have tried the following: SELECT SUM(COALESCE(capacity, 0)) FROM objects WHERE null IS NOT NULL; Result: sum ----- (1 row) Subquestion: wouldn't the above work in Oracle, using SUM(NVL(capacity, 0)) ? 回答1: From the documentation page about aggregate functions: It should be noted that except for count , these functions return a null value when no rows are selected . In particular, sum of no rows returns null, not zero as one might

ios most efficient way to get average value while also filtering out some objects

给你一囗甜甜゛ 提交于 2019-12-04 16:55:37
I'm trying to get the average value of an attribute in a child entity while also trying to only include a select set of records. I have two entities in my Core Data model: Invoice and InvoiceDetail. Invoice:<br> invoiceNum - attribute<br> invoiceDate - attribute<br> invoiceDetails - one-to-many relationship to InvoiceDetail InvoiceDetail:<br> itemAmount - attribute<br> itemType - attribute<br> invoice - one-to-one relationship to Invoice<br> If I wanted to just get the average value of itemAmount for an entire invoice, I would use the following (invoice is an NSManagedObject): float avgAmount

Running totals in a SQL view

余生颓废 提交于 2019-12-04 15:34:05
I am trying to get running totals in my View in SQL Server 2008 Here is my tables BankAccounts ------------ AccountID (KEY) Name Created Transactions ------------ TransactionID (KEY) Description Credit Debit TransDate Created AccountID Here is my query so far.. SELECT t.Created, t.Description, t.Credit, t.Debit, t.TransDate, t.TransactionID, ba.AccountID, (isnull(t.Credit,0)-isnull(t.Debit,0))+COALESCE((SELECT SUM(isnull(Credit,0)) - SUM(isnull(Debit,0)) FROM Transactions b WHERE b.TransDate < t.TransDate and b.AccountID = t.AccountID),0) AS RunningTotal FROM Transactions t INNER JOIN dbo

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

橙三吉。 提交于 2019-12-04 12:41:47
I'm preforming an aggregate function on multiple records, which are grouped by a common ID. The problem is, I also want to export some other fields, which might be different within the grouped records, but I want to get those certain fields from one of the records (the first one, according to the query's ORDER BY). Starting point example: SELECT customer_id, sum(order_total), referral_code FROM order GROUP BY customer_id ORDER BY date_created I need to query the referral code, but doing it outside of an aggregate function means I have to group by that field as well, and that's not what I want

SQLITE: merging rows into single row if they share a column

孤人 提交于 2019-12-04 12:24:54
问题 From a previous post, I have the following view in sqlite3: CREATE View AttendeeTableView AS SELECT (LastName || " " || FirstName) as AttendeeName, CompanyName, PhotoURI, CompanyAttendeeRelation.CompanyId, CompanyAttendeeRelation.AttendeeId FROM Attendee JOIN CompanyAttendeeRelation on CompanyAttendeeRelation.AttendeeId = Attendee.AttendeeId ORDER BY LastName; Now, since the data is generated from a many-to-many relation between Attendee and Company , I can get results such as: Doe John |

How do I calculate a running SUM on a SQLite query?

核能气质少年 提交于 2019-12-04 10:46:11
问题 How do I get a column that is the sum of all the values before of another column? 回答1: You can do it by joining the table with itself (performing a so-called Cartesian or cross join). See the following example. SELECT a.name, a.gdppc, SUM(b.gdppc) FROM gdppc AS a, gdppc AS b WHERE b.gdppc <= a.gdppc GROUP BY b.id ORDER BY a.gdppc; Given a table containing countries and their per capita GDP it will give you a running total of the GDP figure. Democratic Republic of Congo|329.645|329.645

Group by column “grp” and compress DataFrame - (take last not null value for each column ordering by column “ord”)

血红的双手。 提交于 2019-12-04 09:46:30
Assuming I have the following DataFrame: +---+--------+---+----+----+ |grp|null_col|ord|col1|col2| +---+--------+---+----+----+ | 1| null| 3|null| 11| | 2| null| 2| xxx| 22| | 1| null| 1| yyy|null| | 2| null| 7|null| 33| | 1| null| 12|null|null| | 2| null| 19|null| 77| | 1| null| 10| s13|null| | 2| null| 11| a23|null| +---+--------+---+----+----+ here is the same sample DF with comments, sorted by grp and ord : scala> df.orderBy("grp", "ord").show +---+--------+---+----+----+ |grp|null_col|ord|col1|col2| +---+--------+---+----+----+ | 1| null| 1| yyy|null| | 1| null| 3|null| 11| # grp:1 - last

SQL Server 2005 Computed Column Result From Aggregate Of Another Table Field's Value

ε祈祈猫儿з 提交于 2019-12-04 09:15:21
Sorry for the long question title. I guess I'm on to a loser on this one but on the off chance. Is it possible to make the calculation of a calculated field in a table the result of an aggregate function applied to a field in another table. i.e. You have a table called 'mug', this has a child called 'color' (which makes my UK head hurt but the vendor is from the US, what you going to do?) and this, in turn, has a child called 'size'. Each table has a field called sold. The size.sold increments by 1 for every mug of a particular colour and size sold. You want color.sold to be an aggregate of

Django Aggregation - Expression contains mixed types. You must set output_field

末鹿安然 提交于 2019-12-04 09:11:00
问题 I'm trying to achive an Aggregation Query and that's my code: TicketGroup.objects.filter(event=event).aggregate( total_group=Sum(F('total_sold')*F('final_price'))) I have 'total_sold' and 'final_price' in TicketGroup object and all what I want to do is sum and multiply values to get the total sold of all TicketGroups together. All I get is this error: Expression contains mixed types. You must set output_field What I am doing wrong, since I'm calling 'total_group' as my output field? Thanks!