Search Results

Search found 19090 results on 764 pages for 'greatest n per group'.

Page 10/764 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Better way to do SELECT with GROUP BY

    - by Luca Romagnoli
    Hi i've wrote a query that works: SELECT `comments`.* FROM `comments` RIGHT JOIN (SELECT MAX( id ) AS id, core_id, topic_id FROM comments GROUP BY core_id, topic_id order by id desc) comm ON comm.id = comments.id LIMIT 10 I want know if it is possible (and how) to rewrite it to get better performance. Thanks

    Read the article

  • cakePHP and GROUP BY

    - by Lizard
    I am trying to solve a hopefully simple problem here is the query I am trying produce: SELECT `categories`.*, COUNT(`entities`.id) FROM `categories` LEFT JOIN `entities` ON (`categories`.`id` = `entities`.`category_id`) GROUP BY `categories`.`id` I am really struggling to do this is in cakePHP 1.2 How would/should I go about doing this... (I am using 'Containable' if that helps) Thanks in advance

    Read the article

  • How to create entities in one Entity group ?

    - by Gopi
    I am building an app based on google app engine (Java) using JDO for persistence. Can someone give me an example or a point me to some code which shows persisting of multiple entities (of same type) using javax.jdo.PersistenceManager.makePersistentAll() within a transaction. Basically I need to understand how to put multiple entites in one Entity Group so that they can be saved using makePersistentAll() inside transaction.

    Read the article

  • MYSQL Select statment Order By with Group By

    - by mouthpiec
    I have the following simple SQL statment SELECT id, name, value_name, value_id FROM table GROUP BY id ORDER BY value_id DESC when grouping I would like to get the value_name and value_id of the tuple where the value_id is the biggest. The way it is i am getting the smallest value. For example 1, name1, valuename, 3 (where i know that there is a value_id of 5) Can you please help?

    Read the article

  • Better mode for do a select with group by

    - by Luca Romagnoli
    Hi i've wrote a query that works: SELECT `comments`.* FROM `comments` RIGHT JOIN (SELECT MAX( id ) AS id, core_id, topic_id FROM comments GROUP BY core_id, topic_id order by id desc) comm ON comm.id = comments.id LIMIT 10 I want know if is possible and how rewrite it for get better performance. thanks

    Read the article

  • sql - getting the id from a row based on a group by

    - by user85116
    Table A tableAID tableBID grade Table B tableBID name description Table A links to Table b from the tableBID found in both tables. If I want to find the row in Table A, which has the highest grade, for each row in Table B, I would write my query like this: select max(grade) from TableA group by tableBID However, I don't just want the grade, I want the grade plus id of that row.

    Read the article

  • MySQL: group by and IF statement

    - by notset
    By default, parent_id = 0. I want to select all records with parent_id = 0 and only the last ones with parent_id 0. I tried this, but it didn't work: SELECT * FROM `articles` IF `parent_id` > 0 THEN GROUP BY `parent_id` HAVING COUNT(`parent_id`) >= 1 END; ORDER BY `time` DESC What could be the solution?

    Read the article

  • Rails ActiveRecord friendly code from a Complex Join, Sum, and Group query

    - by Chad M
    PROBLEM Hello, I am having no luck trying to break down this SQL statement into ActiveRecord/Rails friendly code and I'd like to learn how I can avoid a find_by_sql statement in this situation. Scenario I have users that create audits when they perform an action. Each audit is of a specific audit_activity. Each audit_activity is worth a certain number of points, based on score_weight. I need to find the total scores of each user, based on their total accumulated audit_activity score_weights. Eventually I'll need to rank them which means adding a sort to this as well. My Code Here is my sql and simplified versions of the tables in question. Any thoughts? SQL with full column names (for clarity) SELECT users.id, u.email, SUM(audit_activity.score_weight) FROM users JOIN audits ON users.id = audits.user_id JOIN audit_activities ON audit_activities.id = audits.audit_activity_id GROUP BY users.id; Models: User, Audit, AuditActivity User fields: id, email class User < ActiveRecord::Base include Clearance::User has_many :audits end Audit fields: id, user_id, audit_activity_id class Audit < ActiveRecord::Base belongs_to :user belongs_to :audit_activity end AuditActivity fields: id, score_weight class AuditActivity < ActiveRecord::Base has_many :audits end Example Data Here is a set of SQL statements so you can play with similar data I'm working with and see what comes up when the concerned query is run. You should just be able to copy/paste the whole thing into a database query browser. CREATE TABLE users( id INTEGER NOT NULL, email TEXT (25), PRIMARY KEY (id) ); CREATE TABLE audits( id INTEGER NOT NULL, user_id INTEGER, audit_activity_id INTEGER, PRIMARY KEY (id) ); CREATE TABLE audit_activities( id INTEGER NOT NULL, score_weight INTEGER, PRIMARY KEY (id) ); INSERT INTO users(id, email) VALUES(1, "[email protected]"); INSERT INTO users(id, email) VALUES(2, "[email protected]"); INSERT INTO users(id, email) VALUES(3, "[email protected]"); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(1, 1, 1); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(2, 1, 2); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(3, 1, 1); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(4, 1, 3); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(5, 1, 1); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(6, 1, 4); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(7, 2, 4); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(8, 2, 4); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(9, 2, 4); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(10, 3, 3); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(11, 3, 2); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(12, 3, 2); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(13, 3, 2); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(14, 3, 3); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(15, 3, 1); INSERT INTO audits(id, user_id, audit_activity_id) VALUES(16, 3, 1); INSERT INTO audit_activities(id, score_weight) VALUES(1, 1); INSERT INTO audit_activities(id, score_weight) VALUES(2, 2); INSERT INTO audit_activities(id, score_weight) VALUES(3, 7); INSERT INTO audit_activities(id, score_weight) VALUES(4, 11); The Query Again, here is the query. SELECT u.id, u.email, SUM(aa.score_weight) FROM users u JOIN audits a ON u.id = a.user_id JOIN audit_activities aa ON aa.id = a.audit_activity_id GROUP BY u.id; Many Thanks, Chad

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5: Part 2 – Table per Type (TPT)

    - by mortezam
    In the previous blog post you saw that there are three different approaches to representing an inheritance hierarchy and I explained Table per Hierarchy (TPH) as the default mapping strategy in EF Code First. We argued that the disadvantages of TPH may be too serious for our design since it results in denormalized schemas that can become a major burden in the long run. In today’s blog post we are going to learn about Table per Type (TPT) as another inheritance mapping strategy and we'll see that TPT doesn’t expose us to this problem. Table per Type (TPT)Table per Type is about representing inheritance relationships as relational foreign key associations. Every class/subclass that declares persistent properties—including abstract classes—has its own table. The table for subclasses contains columns only for each noninherited property (each property declared by the subclass itself) along with a primary key that is also a foreign key of the base class table. This approach is shown in the following figure: For example, if an instance of the CreditCard subclass is made persistent, the values of properties declared by the BillingDetail base class are persisted to a new row of the BillingDetails table. Only the values of properties declared by the subclass (i.e. CreditCard) are persisted to a new row of the CreditCards table. The two rows are linked together by their shared primary key value. Later, the subclass instance may be retrieved from the database by joining the subclass table with the base class table. TPT Advantages The primary advantage of this strategy is that the SQL schema is normalized. In addition, schema evolution is straightforward (modifying the base class or adding a new subclass is just a matter of modify/add one table). Integrity constraint definition are also straightforward (note how CardType in CreditCards table is now a non-nullable column). Another much more important advantage is the ability to handle polymorphic associations (a polymorphic association is an association to a base class, hence to all classes in the hierarchy with dynamic resolution of the concrete class at runtime). A polymorphic association to a particular subclass may be represented as a foreign key referencing the table of that particular subclass. Implement TPT in EF Code First We can create a TPT mapping simply by placing Table attribute on the subclasses to specify the mapped table name (Table attribute is a new data annotation and has been added to System.ComponentModel.DataAnnotations namespace in CTP5): public abstract class BillingDetail {     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } } [Table("BankAccounts")] public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } [Table("CreditCards")] public class CreditCard : BillingDetail {     public int CardType { get; set; }     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } If you prefer fluent API, then you can create a TPT mapping by using ToTable() method: protected override void OnModelCreating(ModelBuilder modelBuilder) {     modelBuilder.Entity<BankAccount>().ToTable("BankAccounts");     modelBuilder.Entity<CreditCard>().ToTable("CreditCards"); } Generated SQL For QueriesLet’s take an example of a simple non-polymorphic query that returns a list of all the BankAccounts: var query = from b in context.BillingDetails.OfType<BankAccount>() select b; Executing this query (by invoking ToList() method) results in the following SQL statements being sent to the database (on the bottom, you can also see the result of executing the generated query in SQL Server Management Studio): Now, let’s take an example of a very simple polymorphic query that requests all the BillingDetails which includes both BankAccount and CreditCard types: projects some properties out of the base class BillingDetail, without querying for anything from any of the subclasses: var query = from b in context.BillingDetails             select new { b.BillingDetailId, b.Number, b.Owner }; -- var query = from b in context.BillingDetails select b; This LINQ query seems even more simple than the previous one but the resulting SQL query is not as simple as you might expect: -- As you can see, EF Code First relies on an INNER JOIN to detect the existence (or absence) of rows in the subclass tables CreditCards and BankAccounts so it can determine the concrete subclass for a particular row of the BillingDetails table. Also the SQL CASE statements that you see in the beginning of the query is just to ensure columns that are irrelevant for a particular row have NULL values in the returning flattened table. (e.g. BankName for a row that represents a CreditCard type) TPT ConsiderationsEven though this mapping strategy is deceptively simple, the experience shows that performance can be unacceptable for complex class hierarchies because queries always require a join across many tables. In addition, this mapping strategy is more difficult to implement by hand— even ad-hoc reporting is more complex. This is an important consideration if you plan to use handwritten SQL in your application (For ad hoc reporting, database views provide a way to offset the complexity of the TPT strategy. A view may be used to transform the table-per-type model into the much simpler table-per-hierarchy model.) SummaryIn this post we learned about Table per Type as the second inheritance mapping in our series. So far, the strategies we’ve discussed require extra consideration with regard to the SQL schema (e.g. in TPT, foreign keys are needed). This situation changes with the Table per Concrete Type (TPC) that we will discuss in the next post. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • What happens when you uninstall a per-user installation?

    - by CraigJ
    What happens if an MSI installation is set to install as per-user, and 3 different users log on and each install the app? Will Windows Installer recognise that the same MSI has already been installed into Program Files and therefore it doesn't need to install it again? What happens if one of the 3 users then uninstalls the app while they are logged in? Will Windows Installer recognise that 2 other users still need the app to be installed and therefore leave alone the app folder in Program Files?

    Read the article

  • SQL Max Group By Query Help

    - by Hcabnettek
    Hi All, I have a quick question. How do I select the two values I need in one query? Currently I'm doing this, which works fine, but it's obviously running two queries when one should do the trick. I tried MAX(columnA) and GROUP BY ColumnB, but that returns multiple row. I only want one row returned. DECLARE @biID bigint , @dtThreshold DateTime SELECT @biID = MAX(biID) FROM tbPricingCalculationCount WITH (NOLOCK) SELECT @dtThreshold = dtDateTime FROM tbPricingCalculationCount WITH (NOLOCK) WHERE biID = @biID I would like both those variables to be set correctly in one query. How can I do that? Thanks, ~ck

    Read the article

  • Reading Local Group Policy / Active Directory Settings

    - by Shinobi
    I'm writing a C# program that will enforce password complexity in accordance with the Windows Group Policy setting "Password must meet complexity requirements". Specifically, if that policy is set to Enabled either on the local machine (if it's not part of a domain) or by the Domain Security Policy (for domain members), then my software needs to enforce a complex password for its own internal security. The issue is that I can't figure out how to read that GPO setting. Google searches have indicated that I can read GPO settings with one of these two APIs: the System.DirectoryServices library in .NET Framework, and Windows Management Instrumentation (WMI), but I haven't had any success so far. Any insights would be helpful.

    Read the article

  • MySQL select using datetime, group by date only

    - by Matt
    Is is possible to select a datetime field from a MySQL table and group by the date only? I'm trying to output a list of events that happen at multiple times, grouped by the date it happened on. My table/data looks like this: (the timestamp is a datetime field) 1. 2010-03-21 18:00:00 Event1 2. 2010-03-21 18:30:00 Event2 3. 2010-03-30 13:00:00 Event3 4. 2010-03-30 14:00:00 Event4 I want to output something like this: March 21st 1800 - Event 1 1830 - Event 2 March 30th 1300 - Event 3 1400 - Event 4 Thanks!

    Read the article

  • Specify which row to return on SQLite Group By

    - by lozzar
    I'm faced with a bit of a difficult problem. I store all the versions of all documents in a single table. Each document has a unique id, and the version is stored as an integer which is incremented everytime there is a new version. I need a query that will only select the latest version of each document from the database. While using GROUP BY works, it appears that it will break if the versions are not inserted in the database in the order of version (ie. it takes the maximum ROWID which will not always be the latest version). Note, that the latest version of each document will most likely be a different number (ie. document A is at version 3, and document B is at version 6). I'm at my wits end, does anybody know how to do this (select all the documents, but only return a single record for each document_id, and that the record returned should have the highest version number)?

    Read the article

  • mysql query: SELECT DISTINCT column1, GROUP BY column2

    - by Adam
    Right now I have the following query: SELECT name, COUNT(name), time, price, ip, SUM(price) FROM tablename WHERE time >= $yesterday AND time <$today GROUP BY name And what I'd like to do is add a DISTINCT by column 'ip', i.e. SELECT DISTINCT ip FROM tablename So my final output would be all the columns, from all the rows that where time is today, grouped by name (with name count for each repeating name) and no duplicate ip addresses. What should my query look like? (or alternatively, how can I add the missing filter to the output with php)? Thanks in advance.

    Read the article

  • Grouping with operands question

    - by Filip
    I have a table: mysql> desc kursy_bid; +-----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+-------+ | datetime | datetime | NO | PRI | NULL | | | currency | varchar(6) | NO | PRI | NULL | | | value | varchar(10) | YES | | NULL | | +-----------+-------------+------+-----+---------+-------+ 3 rows in set (0.01 sec) I would like to select some rows from a table, grouped by some time interval (can be one day) where I will have the first row and the last row of the group, the max(value) and min(value). I tried: select datetime, (select value order by datetime asc limit 1) open, (select value order by datetime desc limit 1) close, max(value), min(value) from kursy_bid_test where datetime > '2009-09-14 00:00:00' and currency = 'eurpln' group by month(datetime), day(datetime), hour(datetime); but the output is: | open | close | datetime | max(value) | min(value) | +--------+--------+---------------------+------------+------------+ | 1.4581 | 1.4581 | 2009-09-14 00:00:05 | 4.1712 | 1.4581 | | 1.4581 | 1.4581 | 2009-09-14 01:00:01 | 1.4581 | 1.4581 | As you see open and close is the same (but they shouldn't be). What should be the query to do what I want?

    Read the article

  • sql select statement with a group by

    - by user85116
    I have data in 2 tables, and I want to create a report. Table A: tableAID (primary key) name Table B: tableBID (primary key) grade tableAID (foreign key, references Table A) There is much more to both tables, but those are the relevant columns. The query I want to run, conceptually, is this: select TableA.name, avg(TableB.grade) where TableB.tableAID = TableA.tableAID The problem of course is that I'm using an aggregate function (avg), and I can rewrite it like this: select avg(grade), tableAID from TableB group by tableAID but then I only get the ID of TableA, whereas I really need that name column which appears in TableA, not just the ID. Is it possible to write a query to do this in one statement, or would I first need to execute the second query I listed, get the list of id's, then query each record in TableA for the name column... seems to me I'm missing something obvious here, but I'm (quite obviously) not an sql guru...

    Read the article

  • Top x rows and group by (again)

    - by Tibor Szasz
    Hello, I know it's a frequent question but I just can't figure it out and the examples I found didn't helped. What I learned, the best strategy is to try to find the top and bottom values of the top range and then select the rest, but implementing is a bit tricky. Example table: id | title | group_id | votes I'd like to get the top 3 voted rows from the table, for each group. I'm expecting this result: 91 | hello1 | 1 | 10 28 | hello2 | 1 | 9 73 | hello3 | 1 | 8 84 | hello4 | 2 | 456 58 | hello5 | 2 | 11 56 | hello6 | 2 | 0 17 | hello7 | 3 | 50 78 | hello8 | 3 | 9 99 | hello9 | 3 | 1 I've fond complex queries and examples, but they didn't really helped.

    Read the article

  • SQL vs MySQL: Rules about aggregate operations and GROUP BY

    - by Phazyck
    In this book I'm currently reading while following a course on databases, the following example of an illegal query using an aggregate operator is given: Find the name and age of the oldest sailor. Consider the following attempt to answer this query: SELECT S.name, S.age FROM Sailors.S The intent is for this query to return not only the maximum age but also the name of the sailors having that age. However, this query is illegal in SQL--if the SELECT clause uses an aggregate operation, then it must use only aggregate operations unless the query contains a GROUP BY clause! Some time later while doing an exercise using MySQL, I faced a similar problem, and made a mistake similar to the one mentioned. However, MySQL didn't complain and just spit out some tables which later turned out not be what I needed. Is the query above really illegal in SQL, but legal in MySQL, and if so, why is that? In what situation would one need to make such a query?

    Read the article

  • MySQL: filling empty fields with zeroes when using GROUP BY

    - by SaltLake
    I've got MySQL table CREATE TABLE cms_webstat ( ID int NOT NULL auto_increment PRIMARY KEY, TIMESTAMP_X timestamp DEFAULT CURRENT_TIMESTAMP, # ... some other fields ... ) which contains statistics about site visitors. For getting visits per hour I use SELECT hour(TIMESTAMP_X) as HOUR , count(*) AS HOUR_STAT FROM cms_webstat GROUP BY HOUR ORDER BY HOUR DESC which gives me | HOUR | HOUR_STAT | | 24 | 15 | | 23 | 12 | | 22 | 9 | | 20 | 3 | | 18 | 2 | | 15 | 1 | | 12 | 3 | | 9 | 1 | | 3 | 5 | | 2 | 7 | | 1 | 9 | | 0 | 12 | And I'd like to get following: | HOUR | HOUR_STAT | | 24 | 15 | | 23 | 12 | | 22 | 9 | | 21 | 0 | | 20 | 3 | | 19 | 0 | | 18 | 2 | | 17 | 0 | | 16 | 0 | | 15 | 1 | | 14 | 0 | | 13 | 0 | | 12 | 3 | | 11 | 0 | | 10 | 0 | | 9 | 1 | | 8 | 0 | | 7 | 0 | | 6 | 0 | | 5 | 0 | | 4 | 0 | | 3 | 5 | | 2 | 7 | | 1 | 9 | | 0 | 12 | How should I modify the query to get such result? Thanks.

    Read the article

  • Getting counts of 0 from a query with a double group by

    - by Maltiriel
    I'm trying to write a query that gets the counts for a table (call it item) categorized by two different things, call them type and code. What I'm hoping for as output is the following: Type Code Count 1 A 3 1 B 0 1 C 10 2 A 0 2 B 13 2 C 2 And so forth. Both type and code are found in lookup tables, and each item can have just one type but more than one code, so there's also a pivot (aka junction or join) table for the codes. I have a query that can get this result: Type Code Count 1 A 3 1 C 10 2 B 13 2 C 2 and it looks like (with join conditions omitted): SELECT typelookup.name, codelookup.name, COUNT(item.id) FROM typelookup LEFT OUTER JOIN item JOIN itemcodepivot RIGHT OUTER JOIN codelookup GROUP BY typelookup.name, codelookup.name Is there any way to alter this query to get the results I'm looking for? This is in MySQL, if that matters. I'm not actually sure this is possible all in one query, but if it is I'd really like to know how. Thanks for any ideas.

    Read the article

  • Working by group by for grouping data into string format

    - by Shantanu Gupta
    I have a table that contains some data given below. It uses a tree like structure i.e. Department SubD1, SubD2 ..... PreSubD1, PreSubD1... PreSubD2, PreSubD2... pk_map_id preferences ImmediateParent Department_Id -------------------- -------------------- -------------------- -------------------- 20 14 5 1 21 15 5 1 22 16 6 1 23 9 4 2 24 4 3 2 25 24 20 2 26 25 20 2 27 23 13 2 I want to group my records on behalf of department then immediate parent then preferences each seperated by ',' i.e. department Immediate Parent preferences 1 5,6 14,15,16 2 4,3,20,13 9,4,24,25,23 and this table also Immediate parent preferences 5 14,15 6 16 4 9 3 4 20 24,25 13 13 In actual scenario all these are my ids which are to be replaced by their string fields. I am using sql server 2k5

    Read the article

  • how to select and group mysql data based on the follwoing table

    - by user1151680
    how can I achieve the desired result in mysql if my table looks like this. result|year 1 |2011 2 |2011 1 |2011 0 |2011 1 |2012 2 |2012 1 = Won, 2 = lost, 0 = draw Every year can have multiple values like this. Not sure how I can get the desired result like below. year won lost draw totalPlayed 2011 2 1 1 3 2012 1 1 0 2 I have tried the following query but does not get the desired result select year, league_types.league_name, sum(if(result = 1,1,0)) as won, sum(if(result = 0,1,0)) as draw, sum(if(result = 4,1,0)) as noResult, sum(if(result = 2,1,0)) as lost, sum(if(result = 3,1,0)) as tied, sum(if(result > 0 and result < 4,1,0)) as played from match_score_card inner join fixtures on match_score_card.match_id = fixtures.match_id inner join league_types on fixtures.league_id = league_types.league_id where team_id = 1 group by year order by year desc

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >