Search Results

Search found 282 results on 12 pages for 'aggregation'.

Page 3/12 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Custom aggregation in GROUP BY clause

    - by Rire1979
    If I have a table with a schema like this table(Category, SubCategory1, SubCategory2, Status) I would like to group by Category, SubCategory1 and aggregate the Status such that if not all Status values over the group have a certain value Status will be 0 otherwise 1. So my result set will look like (Category, SubCategory1, Status) I don't want to write a function. I would like to do it inside the query.

    Read the article

  • Objective C: CoreData and aggregation

    - by Ralf
    Given a CoreData-Entity with an date (days) and an ammount called Transaction. Is it with CoreData possible (and how) to aggregate/group the 'table' (with all Transactions) by Date and calculate the sum of the day in a second column/attribute? (the SQL-Solution would be SELECT date, sum(ammount) FROM transaction GROUP BY date)

    Read the article

  • SQL Server: collect values in an aggregation temporarily and reuse in the same query

    - by Erwin Brandstetter
    How do I accumulate values in t-SQL? AFAIK there is no ARRAY type. I want to reuse the values like demonstrated in this PostgreSQL example using array_agg(). SELECT a[1] || a[i] AS foo ,a[2] || a[5] AS bar -- assuming we have >= 5 rows for simplicity FROM ( SELECT array_agg(text_col ORDER BY text_col) AS a ,count(*)::int4 AS i FROM tbl WHERE id between 10 AND 100 ) x How would I best solve this with t-SQL? Best I could come up with are two CTE and subselects: ;WITH x AS ( SELECT row_number() OVER (ORDER BY name) AS rn ,name AS a FROM #t WHERE id between 10 AND 100 ), i AS ( SELECT count(*) AS i FROM x ) SELECT (SELECT a FROM x WHERE rn = 1) + (SELECT a FROM x WHERE rn = i) AS foo ,(SELECT a FROM x WHERE rn = 2) + (SELECT a FROM x WHERE rn = 5) AS bar FROM i Test setup: CREATE TABLE #t( id INT PRIMARY KEY ,name NVARCHAR(100)) INSERT INTO #t VALUES (3 , 'John') ,(5 , 'Mary') ,(8 , 'Michael') ,(13, 'Steve') ,(21, 'Jack') ,(34, 'Pete') ,(57, 'Ami') ,(88, 'Bob') Is there a simpler way?

    Read the article

  • Django aggregation on a date range

    - by klaut
    Hi all, I have been lurking and learning in here for a while. Now i have a problem that somehow i cannot see an easy solution. In order to learn django i am bulding an app that basically keeps track of booked items. What I would like to do is to show how many days per month for a selected year one item has been booked. i have the following models: Asset(Model) BookedAsset(Model): asset = models.ForeignKey(Asset) startdate = models.DateField() enddate = models.DateField() So having the following entries: asset 1, 2010-02-11, 2010-02-13 asset 2, 2010-03-12, 2010-03-14 asset 1, 2010-04-30, 2010-05-01 I would like to get returned the following: asset 1 asset 2 ------- ------- Jan = 0 Jan = 0 Feb = 2 Feb = 0 Mar = 0 Mar = 2 Apr = 1 Apr = 0 May = 1 May = 0 Jun = 0 Jun = 0 Jul = 0 Jul = 0 Aug = 0 Aug = 0 Sep = 0 Sep = 0 Oct = 0 Oct = 0 Nov = 0 Nov = 0 Dec = 0 Dec = 0 I know i need to first get the number of days in a date range (and keep track if they fall out of the current month and into the next month) and then do an agregate on the number of days. I am just stuck on how to do it elegantly in Django. Any help (or hint in the right direction) is greatly appreciated.

    Read the article

  • ResultSet and aggregation

    - by kachanov
    Ok, I admit my situation is special There is a data system that supports SQL-92 and JDBC interface However the SQL requets are pretty expensive, and in my application I need to retreive the same data multiple times and aggregate it ("group by") on different fields to show different dimensions of the same data. For example on one screen I have three tables that show the same set or records but aggregated by City (1st grid), by Population (2nd grid), by number of babies (3rd grid) This amounts to 3 SQL queries (which is very slow), UNLESS anyone of you can suggest any idea any library from apache commons or from google code, so that I can select all records into ResultSet and get 3 arrays of data group by different fields from this single ResultSet. Am I'm missing some obvious and unexpected solution to this problem?

    Read the article

  • Barplot in R, aggregation of sampled data

    - by Felix
    Hello, I want an stacked barplot, or at least two barplots (histogramms) of the data below. But I cant't figure out how. plot(online) is not the solution, I´m looking for. Please see below. online offline 1 sehrwichtig wichtig 2 wichtig unwichtig 3 sehrwichtig unwichtig 4 sehrwichtig sehrwichtig 5 sehrwichtig sehrwichtig 6 sehrwichtig unwichtig 7 sehrwichtig unwichtig 8 wichtig wichtig 9 wichtig unwichtig 10 sehrwichtig sehrwichtig 11 sehrwichtig wichtig 12 sehrwichtig unwichtig 13 wichtig sehrwichtig 14 sehrwichtig wichtig I know I need a step, where the data is aggregated to: online offline sehrwichtig 6 7 unwichtig 0 1 wichtig 3 5 But how?

    Read the article

  • rails data aggregation

    - by ash34
    Hi, I have to create a hash of the form h[:bill] = ["Billy", "NA", 20, "PROJ_A"] by login where 20 is the cumulative number of hours reported by the login for all task transactions returned by the query where each login has multiple reported transactions. Did I do this in a bad way or this seems alright. h = Hash.new Task.find_each(:include => [:user], :joins => :user, :conditions => ["from_date >= ? AND from_date <= ? AND category = ?", Date.today - 30, Date.today + 30, 'PROJ1']) do |t| h[t.login.intern] = [t.user.name, 'NA', h[t.login.intern].nil? ? (t.hrs_per_day * t.num_days) : h[t.login.intern][2] + (t.hrs_day * t.workdays), t.category] end Also if I have to aggregate this data not just by login but login and category how do I accomplish this? thanks, ash

    Read the article

  • SQL aggregation query, grouping by entries in junction table

    - by cm007
    I have TableA in a many-to-many relationship with TableC via TableB. That is, TableA TableB TableC id | val fkeyA | fkeyC id | data I wish the do select sum(val) on TableA, grouping by the relationship(s) to TableC. Every entry in TableA has at least one relationship with TableC. For example, TableA 1 | 25 2 | 30 3 | 50 TableB 1 | 1 1 | 2 2 | 1 2 | 2 2 | 3 3 | 1 3 | 2 should output 75 30 since rows 1 and 3 in Table have the same relationships to TableC, but row 2 in TableA has a different relationship to TableC. How can I write a SQL query for this?

    Read the article

  • Request for advice about class design, inheritance/aggregation

    - by Lasse V. Karlsen
    I have started writing my own WebDAV server class in .NET, and the first class I'm starting with is a WebDAVListener class, modelled after how the HttpListener class works. Since I don't want to reimplement the core http protocol handling, I will use HttpListener for all its worth, and thus I have a question. What would the suggested way be to handle this: Implement all the methods and properties found inside HttpListener, just changing the class types where it matters (ie. the GetContext + EndGetContext methods would return a different class for WebDAV contexts), and storing and using a HttpListener object internally Construct WebDAVListener by passing it a HttpListener class to use? Create a wrapper for HttpListener with an interface, and constrct WebDAVListener by passing it an object implementing this interface? If going the route of passing a HttpListener (disguised or otherwise) to the WebDAVListener, would you expose the underlying listener object through a property, or would you expect the program that used the class to keep a reference to the underlying HttpListener? Also, in this case, would you expose some of the methods of HttpListener through the WebDAVListener, like Start and Stop, or would you again expect the program that used it to keep the HttpListener reference around for all those things? My initial reaction tells me that I want a combination. For one thing, I would like my WebDAVListener class to look like a complete implementation, hiding the fact that there is a HttpListener object beneath it. On the other hand, I would like to build unit-tests without actually spinning up a networked server, so some kind of mocking ability would be nice to have as well, which suggests I would like the interface-wrapper way. One way I could solve this would be this: public WebDAVListener() : WebDAVListener(new HttpListenerWrapper()) { } public WebDAVListener(IHttpListenerWrapper listener) { } And then I would implement all the methods of HttpListener (at least all those that makes sense) in my own class, by mostly just chaining the call to the underlying HttpListener object. What do you think? Final question: If I go the way of the interface, assuming the interface maps 1-to-1 onto the HttpListener class, and written just to add support for mocking, is such an interface called a wrapper or an adapter?

    Read the article

  • help with t-sql data aggregation

    - by stackoverflowuser
    Based on the following table Area S1 S2 S3 S4 -------------------- A1 5 10 20 0 A2 11 19 15 20 A3 0 0 0 20 I want to generate an output that will give the number of columns not having "0". So the output would be Area S1 S2 S3 S4 Count ------------------------- A1 5 10 20 0 3 A2 11 19 15 20 4 A3 0 0 0 20 1

    Read the article

  • Aggregation over a few models - Django

    - by RadiantHex
    Hi folks, I'm trying to compute the average of a field over various subsets of a queryset. Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level')) This works perfectly! But... if I try to compute it for the top 50 players it does not work. Player.objects.order_by('-score').filter(sex='male')[:50].aggregate(Avg('level')) This last one returns the exact same result as the query above it, which is wrong. What am I doing wrong? Help would be very much appreciated!

    Read the article

  • SQL Command Not Properly Ended (Nested Aggregation with Group-by)

    - by snowind
    I keep getting this error when I tried to execute this query, although I couldn't figure out what went wrong. I'm using Oracle and JDBC. Here's the query: SELECT Temp.flight_number, Temp.avgprice FROM (SELECT P.flight_number, AVG (P.amount) AS avgprice FROM purchase P GROUP BY P.flight_number) AS Temp WHERE Temp.avgprice = (SELECT MAX (Temp.avgprice) FROM Temp) I'm trying to get the maximum of average price of the tickets that customers have booked, group by flight_number.

    Read the article

  • Client-Side Dynamic Removal of <script> Tags in <head>

    - by merv
    Is it possible to remove script tags in the <head> of an HTML document client-side and prior to execution of those tags? On the server-side I am able to insert a <script> above all other <script> tags in the <head>, except one, and I would like to be able to remove all subsequent scripts. I do not have the ability to remove <script> tags from the server side. What I've tried: (function (c,h) { var i, s = h.getElementsByTagName('script'); c.log("Num scripts: " + s.length); i = s.length - 1; while(i > 1) { h.removeChild(s[i]); i -= 1; } })(console, document.head); However, the logged number of scripts comes out to only 1, since (as @ryan pointed out) the code is being executed prior to the DOM being ready. Although wrapping the code above in a document.ready event callback does enable proper calculation of the number of <script> tags in the <head>, waiting until the DOM is ready fails to prevent the scripts from loading. Is there a reliable means of manipulating the HTML prior to the DOM being ready? Background If you want more context, this is part of an attempt to consolidate scripts where no option for server-side aggregation is available. Many of the JS libraries being loaded are from a CMS with limited configuration options. The content is mostly static, so there is very little concern about manually aggregating the JavaScript and serving it from a different location. Any suggestions for alternative applicable aggregation techniques would also be welcome.

    Read the article

  • SPARC T4-2 Produces World Record Oracle Essbase Aggregate Storage Benchmark Result

    - by Brian
    Significance of Results Oracle's SPARC T4-2 server configured with a Sun Storage F5100 Flash Array and running Oracle Solaris 10 with Oracle Database 11g has achieved exceptional performance for the Oracle Essbase Aggregate Storage Option benchmark. The benchmark has upwards of 1 billion records, 15 dimensions and millions of members. Oracle Essbase is a multi-dimensional online analytical processing (OLAP) server and is well-suited to work well with SPARC T4 servers. The SPARC T4-2 server (2 cpus) running Oracle Essbase 11.1.2.2.100 outperformed the previous published results on Oracle's SPARC Enterprise M5000 server (4 cpus) with Oracle Essbase 11.1.1.3 on Oracle Solaris 10 by 80%, 32% and 2x performance improvement on Data Loading, Default Aggregation and Usage Based Aggregation, respectively. The SPARC T4-2 server with Sun Storage F5100 Flash Array and Oracle Essbase running on Oracle Solaris 10 achieves sub-second query response times for 20,000 users in a 15 dimension database. The SPARC T4-2 server configured with Oracle Essbase was able to aggregate and store values in the database for a 15 dimension cube in 398 minutes with 16 threads and in 484 minutes with 8 threads. The Sun Storage F5100 Flash Array provides more than a 20% improvement out-of-the-box compared to a mid-size fiber channel disk array for default aggregation and user-based aggregation. The Sun Storage F5100 Flash Array with Oracle Essbase provides the best combination for large Oracle Essbase databases leveraging Oracle Solaris ZFS and taking advantage of high bandwidth for faster load and aggregation. Oracle Fusion Middleware provides a family of complete, integrated, hot pluggable and best-of-breed products known for enabling enterprise customers to create and run agile and intelligent business applications. Oracle Essbase's performance demonstrates why so many customers rely on Oracle Fusion Middleware as their foundation for innovation. Performance Landscape System Data Size(millions of items) Database Load(minutes) Default Aggregation(minutes) Usage Based Aggregation(minutes) SPARC T4-2, 2 x SPARC T4 2.85 GHz 1000 149 398* 55 Sun M5000, 4 x SPARC64 VII 2.53 GHz 1000 269 526 115 Sun M5000, 4 x SPARC64 VII 2.4 GHz 400 120 448 18 * – 398 mins with CALCPARALLEL set to 16; 484 mins with CALCPARALLEL threads set to 8 Configuration Summary Hardware Configuration: 1 x SPARC T4-2 2 x 2.85 GHz SPARC T4 processors 128 GB memory 2 x 300 GB 10000 RPM SAS internal disks Storage Configuration: 1 x Sun Storage F5100 Flash Array 40 x 24 GB flash modules SAS HBA with 2 SAS channels Data Storage Scheme Striped - RAID 0 Oracle Solaris ZFS Software Configuration: Oracle Solaris 10 8/11 Installer V 11.1.2.2.100 Oracle Essbase Client v 11.1.2.2.100 Oracle Essbase v 11.1.2.2.100 Oracle Essbase Administration services 64-bit Oracle Database 11g Release 2 (11.2.0.3) HP's Mercury Interactive QuickTest Professional 9.5.0 Benchmark Description The objective of the Oracle Essbase Aggregate Storage Option benchmark is to showcase the ability of Oracle Essbase to scale in terms of user population and data volume for large enterprise deployments. Typical administrative and end-user operations for OLAP applications were simulated to produce benchmark results. The benchmark test results include: Database Load: Time elapsed to build a database including outline and data load. Default Aggregation: Time elapsed to build aggregation. User Based Aggregation: Time elapsed of the aggregate views proposed as a result of tracked retrieval queries. Summary of the data used for this benchmark: 40 flat files, each of size 1.2 GB, 49.4 GB in total 10 million rows per file, 1 billion rows total 28 columns of data per row Database outline has 15 dimensions (five of them are attribute dimensions) Customer dimension has 13.3 million members 3 rule files Key Points and Best Practices The Sun Storage F5100 Flash Array has been used to accelerate the application performance. Setting data load threads (DLTHREADSPREPARE) to 64 and Load Buffer to 6 improved dataloading by about 9%. Factors influencing aggregation materialization performance are "Aggregate Storage Cache" and "Number of Threads" (CALCPARALLEL) for parallel view materialization. The optimal values for this workload on the SPARC T4-2 server were: Aggregate Storage Cache: 32 GB CALCPARALLEL: 16   See Also Oracle Essbase Aggregate Storage Option Benchmark on Oracle's SPARC T4-2 Server oracle.com Oracle Essbase oracle.com OTN SPARC T4-2 Server oracle.com OTN Oracle Solaris oracle.com OTN Oracle Database 11g Release 2 Enterprise Edition oracle.com OTN Disclosure Statement Copyright 2012, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. Results as of 28 August 2012.

    Read the article

  • Can a problem have a relation of aggregation and composition both between two classes at same point

    - by learner
    Can a problem have a relation of aggregation and composition both between two classes at same point of time? Like any real time scenario where there can be aggregation corresponding to one method and composition related to other method. I m unable to figure out any scenario where both composition and aggregation occurs simultaneously between two classes. Any help will be appreciable.

    Read the article

  • How to use Private Inheritence aka C++ in C# and Why not it is present in C#

    - by Vijay
    I know that private inheritance is supported in C++ and only public inheritance is supported in C#. I also came across an article which says that private inheritance usually defines a HAS-A relationship and kind of an aggregation relationship between the classes. EDIT: C++ code for private inheritance: The "Car has-a Engine" relationship can also be expressed using private inheritance: class Car : private Engine { // Car has-a Engine public: Car() : Engine(8) { } // Initializes this Car with 8 cylinders using Engine::start; // Start this Car by starting its Engine }; Now, Is there a way to create a HAS-A relationship between C# classes which is one of the thing that I would like to know - HOW? Another curious question is why doesn't C# support the private (and also protected) inheritance ? - Is not supporting multiple implementation inheritance a valid reason or any other? Is private (and protected) inheritance planned for future versions of C#? Will supporting the private (and protected) inheritance in C# make it a better and widely used language?

    Read the article

  • Django model manager didn't work with related object when I do aggregated query

    - by Satoru.Logic
    Hi, all. I'm having trouble doing an aggregation query on a many-to-many related field. Let's begin with my models: class SortedTagManager(models.Manager): use_for_related_fields = True def get_query_set(self): orig_query_set = super(SortedTagManager, self).get_query_set() # FIXME `used` is wrongly counted return orig_query_set.distinct().annotate( used=models.Count('users')).order_by('-used') class Tag(models.Model): content = models.CharField(max_length=32, unique=True) creator = models.ForeignKey(User, related_name='tags_i_created') users = models.ManyToManyField(User, through='TaggedNote', related_name='tags_i_used') objects_sorted_by_used = SortedTagManager() class TaggedNote(models.Model): """Association table of both (Tag , Note) and (Tag, User)""" note = models.ForeignKey(Note) # Note is what's tagged in my app tag = models.ForeignKey(Tag) tagged_by = models.ForeignKey(User) class Meta: unique_together = (('note', 'tag'),) However, the value of the aggregated field used is only correct when the model is queried directly: for t in Tag.objects.all(): print t.used # this works correctly for t in user.tags_i_used.all(): print t.used #prints n^2 when it should give n Would you please tell me what's wrong with it? Thanks in advance.

    Read the article

  • sort django queryset by latest instance of a subset of related model

    - by rsp
    I have an Order model and order_event model. Each order_event has a foreignkey to order. so from an order instance i can get: myorder.order_event_set. I want to get a list of all orders but i want them to be sorted by the date of the last event. A statement like this works to sort by the latest event date: queryset = Order.objects.all().annotate(latest_event_date=Max('order_event__event_datetime')).order_by('latest_event_date') However, what I really need is a list of all orders sorted by latest date of A SUBSET OF EVENTS. For example my events are categorized into "scheduling", "processing", etc. So I should be able to get a list of all orders sorted by the latest scheduling event. This django doc (https://docs.djangoproject.com/en/dev/topics/db/aggregation/#filter-and-exclude) shows how I can get the latest schedule event using a filter but this excludes orders without a scheduling event. I thought I could combine the filtered queryset with a queryset that includes back those orders that are missing a scheduling event...but I'm not quite sure how to do this. I saw answers related to using python list but it would be much more useful to have a proper django queryset (ie for a view with pagination, etc.)

    Read the article

  • Rails 1.0 - Using composed_of gives me a wrong number of arguments (1 for 5) error

    - by Tristan Havelick
    I am developing a Rails 1.0 application (I can't upgrade, it's a strange situation) for which I am trying to use the :composed_of functionality. I have a class called StreetAddress: class StreetAddress attr_reader :address, :address2, :city, :state_id, :zip_code def initialize(address, address2, city, state_id, zip_code) @address = address @address2 = address2 @city = city @state_id = state_id @zip_code = zip_code end end and a model class called Hotel class Hotel < ActiveRecord::Base composed_of :street_address # ... end which has columns: "id", "brand_id", "code", "location_name", "address", "address2", "city", "state_id", "zip_code", "phone_number", "phone_ext", "fax_number", "time_zone", "url", "room_service_email", "manager_name", "manager_email" However when I try to access the aggregation I get an error: >> h = Hotel.find(1) => #<Hotel:0x38ad718 @attributes={"fax_number"=>"1-623-420-0124", "city"=>"Twin Falls", "address2"=>"285", "brand_id"=>"1", "code"=>"XZWUXUSZ", "manager_email"= >"[email protected]", "url"=>"http://www.xycdkzolukfvu.hom", "ph one_number"=>"1-805-706-9995", "zip_code"=>"72436", "phone_ext"=>"48060", "id"=> "1", "manager_name"=>"Igor Mcdowell", "room_service_email"=>"Duis.risus@Donecvit ae.ca", "time_zone"=>"America/Boise", "state_id"=>"15", "address"=>"P.O. Box 457 , 7405 Dignissim Avenue", "location_name"=>"penatibus et magnis"}> >> h.street_address ArgumentError: wrong number of arguments (1 for 5) from (eval):3:in `initialize' from (eval):3:in `new' from (eval):3:in `street_address' from (irb):6 Why?

    Read the article

  • How to implement child-parent aggregation link in C++?

    - by Giorgio
    Suppose that I have three classes P, C1, C2, composition (strong aggregation) relations between P <>- C1 and P <>- C2, i.e. every instance of P contains an instance of C1 and an instance of C2, which are destroyed when the parent P instance is destroyed. an association relation between instances of C1 and C2 (not necessarily between children of the same P). To implement this, in C++ I normally define three classes P, C1, C2, define two member variables of P of type boost::shared_ptr<C1>, boost::shared_ptr<C2>, and initialize them with newly created objects in P's constructor, implement the relation between C1 and C2 using a boost::weak_ptr<C2> member variable in C1 and a boost::weak_ptr<C1> member variable in C2 that can be set later via appropriate methods, when the relation is established. Now, I also would like to have a link from each C1 and C2 object to its P parent object. What is a good way to implement this? My current idea is to use a simple constant raw pointer (P * const) that is set from the constructor of P (which, in turn, calls the constructors of C1 and C2), i.e. something like: class C1 { public: C1(P * const p, ...) : paren(p) { ... } private: P * const parent; ... }; class P { public: P(...) : childC1(new C1(this, ...)) ... { ... } private: boost::shared_ptr<C1> childC1; ... }; Honestly I see no risk in using a private constant raw pointer in this way but I know that raw pointers are often frowned upon in C++ so I was wondering if there is an alternative solution.

    Read the article

  • How do I aggregate results from an Adjacency list using PHP's SPL

    - by Stephen J. Fuhry
    I've tried using nested sets, and they become very difficult to maintain when dealing with multiple trees and lots of other complications.. I'd like to give PHP's SPL library a stab at this (btw, we are PHP 5.3, MySQL 5.1). Given two datasets: The Groups: +-------+--------+---------------------+---------------+ | id | parent | Category Name | child_key | +-------+--------+---------------------+---------------+ | 11133 | 7707 | Really Cool Products| 47054 | | 7709 | 7708 | 24" Monitors | 57910 | | 7713 | 7710 | Hot Tubs | 35585 | | 7716 | 7710 | Hot Dogs | 00395 | | 11133 | 7707 | Really Cool Products| 66647 | | 7715 | 7710 | Suction Cups | 08396 | +-------+--------+---------------------+---------------+ The Items +------------+------------+-----------+----------+---------+ | child_key | totalprice | totalcost | totalqty | onorder | (jan, feb, mar..) +------------+------------+-----------+----------+---------+ | 24171 | 10.50 | 20.10 | 200 | 100 | | 35685 | 10.50 | 20.10 | 200 | 100 | | 76505 | 10.50 | 20.10 | 200 | 100 | | 04365 | 10.50 | 20.10 | 200 | 100 | | 01975 | 10.50 | 20.10 | 200 | 100 | | 12150 | 10.50 | 20.10 | 200 | 100 | | 40060 | 10.50 | 20.10 | 200 | 100 | | 08396 | 10.50 | 20.10 | 200 | 100 | +------------+------------+-----------+----------+---------+ The figures are actually much more complicated than this (I am actually aggregating a variable amount of months or years over the past 15yrs, so there may need to be 20 columns of aggregated results). I have been trying to figure out RecursiveIterator and IteratorAggregate, but I am having a difficult time finding real world examples that are generic enough to really wrap my head around these classes. Can someone give me a head start?

    Read the article

  • ProgrammingError when aggregating over an annotated & grouped Django ORM query

    - by ento
    I'm trying to construct a query to get the "average, maximum, minimum number of items purchased by a single user". The data source is this simple sales record table: class SalesRecord(models.Model): id = models.IntegerField(primary_key=True) user_id = models.IntegerField() product_code = models.CharField() price = models.IntegerField() created_at = models.DateTimeField() A new record is inserted into this table for every item purchased by a user. Here's my attempt at building the query: q = SalesRecord.objects.all() q = q.values('user_id').annotate( # group by user and count the # of records count=Count('id'), # (= # of items) ).order_by() result = q.aggregate(Max('count'), Min('count'), Avg('count')) When I try to execute the code, a ProgrammingError is raised at the last line: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (SELECT sales_records.user_id AS user_id, COUNT(sales_records.`' at line 1") Django's error screen shows that the SQL is SELECT FROM (SELECT `sales_records`.`player_id` AS `player_id`, COUNT(`sales_records`.`id`) AS `count` FROM `sales_records` WHERE (`sales_records`.`created_at` >= %s AND `sales_records`.`created_at` <= %s ) GROUP BY `sales_records`.`player_id` ORDER BY NULL) subquery It's not selecting anything! Can someone please show me the right way to do this? Hacking Django I've found that clearing the cache of selected fields in django.db.models.sql.BaseQuery.get_aggregation() seems to solve the problem. Though I'm not really sure this is a fix or a workaround. @@ -327,10 +327,13 @@ # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. + self._aggregate_select_cache = None + self.aggregate_select_mask = None for alias, aggregate in self.aggregate_select.items(): if aggregate.is_summary: query.aggregate_select[alias] = aggregate - del obj.aggregate_select[alias] + if alias in obj.aggregate_select: + del obj.aggregate_select[alias] ... yields result: {'count__max': 267, 'count__avg': 26.2563, 'count__min': 1}

    Read the article

  • WPF/MVVM: How can I use several CollectionView`s for aggregated entities ?

    - by msfanboy
    Hello, I have a Customer with Orders and those have products. Everything aggregated with collections of type ObservableCollection. All 3 collections are bound to a datagrid/combobox. I can only make the root collection (ObservableCollection Customers{ get;set;} ) passing to a CollectionView so I can move the current customer within the combobox. But how can I move around the current Order in the datagrid? How to pass the selected Orders to another CollectionView ? Does all this maybe not work?

    Read the article

  • How can I run .aggregate() on a field introduced using .extra(select={...}) in a Django Query?

    - by Jake
    I'm trying to get the count of the number of times a player played each week like this: player.game_objects.extra(select={'week': 'WEEK(`games_game`.`date`)'}).aggregate(count=Count('week')) But Django complains that FieldError: Cannot resolve keyword 'week' into field. Choices are: <lists model fields> I can do it in raw SQL like this SELECT WEEK(date) as week, COUNT(WEEK(date)) as count FROM games_game WHERE player_id = 3 GROUP BY week Is there a good way to do this without executing raw SQL in Django?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >