66

Unfortunately, there is no provision in SQL syntax to say "all columns except this one column". You can achieve your goal by spelling out the remaining list of columns in a row-type expression: SELECT a.id, a.name , json_agg((b.col1, b.col2, b.col3)) AS item FROM a JOIN b ON b.item_id = a.id GROUP BY a.id, a.name; That's short for the ...


36

Let's pretend you've got the white pages of the phone book - remember, that thing Grandpa kept by the fridge so he could call his friends from the war. It's organized by last name, first name. If I asked you to get that phone book and read out the names: SELECT FirstName, LastName FROM dbo.PhoneBook You would usually read them out to me in last name order....


32

This is actually a really bad thing to do IMHO, and it's not supported in most other database platforms. The reasons people do it: they're lazy - I don't know why people think their productivity is improved by writing terse code rather than typing for an extra 40 milliseconds to get much more literal code. The reasons it's bad: it's not self-documenting -...


29

Main problem is the missing index. But there is more. SELECT user_id, count(*) AS ct FROM treenode WHERE project_id = 1 GROUP BY user_id; You have many bigint columns. Probably overkill. Typically, integer is more than enough for columns like project_id and user_id. This would also help the next item. While optimizing the table definition, consider ...


24

The feature of Postgres to be able to use the primary key of a table with GROUP BY and not need to add the other columns of that table in the GROUP BY clause is relatively new and works only for base tables. The optimizer is not (yet?) clever enough to identify primary keys for views, ctes or derived tables (as in your case). You can add the columns you want ...


22

Starting with 9.6 you can simply use - to remove a key from a JSONB: SELECT a.id, a.name, jsonb_agg(to_jsonb(b) - 'item_id') as "item" FROM a JOIN b ON b.item_id = a.id GROUP BY a.id, a.name; to_jsonb(b) will convert the whole row and - 'item_id' will then remove the key with the name item_id the result of that is then aggregated.


21

In SQL Server you can only select columns that are part of the GROUP BY clause, or aggregate functions on any of the other columns. I've blogged about this in detail here. So you have two options: Add the additional columns to the GROUP BY clause: GROUP BY Rls.RoleName, Pro.[FirstName], Pro.[LastName] Add some aggregate function on the relevant columns: ...


18

The LEFT JOIN in @dezso's answer should be good. An index, however, will hardly be useful (per se), because the query has to read the whole table anyway - the exception being index-only scans in Postgres 9.2+ and favorable conditions, see below. SELECT m.hash, m.string, count(m.method) AS method_ct FROM methods m LEFT JOIN nostring n USING (hash) WHERE ...


18

The reason your query did not work as intended: Inner join gives you the intersection of 2 tables. In your case, there was no entry for 5th street in your users table and that is why join did not produce any entry for that. Outer join (right or left) will give the result of inner join and in addition all non-qualifying records from the left or right table ...


17

This is a gaps-and-islands problem. Assuming there are no gaps or duplicates in the same id_set set: WITH partitioned AS ( SELECT *, number - ROW_NUMBER() OVER (PARTITION BY id_set) AS grp FROM atable WHERE status = 'FREE' ), counted AS ( SELECT *, COUNT(*) OVER (PARTITION BY id_set, grp) AS cnt FROM partitioned ) SELECT id_set, ...


16

GROUP BY cannot be used alone because it only returns 1 row per group (category). You can use a sub query with flag = 1 and INNER JOIN: SELECT d1.ID, d1.category, d1.flag FROM data d1 INNER JOIN ( SELECT DISTINCT category FROM data WHERE flag = 1 ) d2 ON d2.category = d1.category ; You can use the EXISTS clause: SELECT d.ID, d.category, d.flag ...


16

1. Window functions plus subqueries Count the steps to form groups, similar to Evan's idea, with modifications and fixes: SELECT id_type , min(date) AS begin , max(date) AS end , count(*) AS row_ct -- optional addition FROM ( SELECT date, id_type, count(step OR NULL) OVER (ORDER BY date) AS grp FROM ( SELECT date, id_type ...


16

You can see the role of this aggregate if no rows match the WHERE clause. SELECT MAX(Revision) FROM dbo.TheOneders WHERE Id = 1 AND 1 = 1 /*To avoid auto parameterisation*/ AND Id%3 = 4 /*always false*/ In that case zero rows go into the aggregate but it still emits one as the correct semantics are to return NULL in this case. This is a ...


14

The conditions in HAVING are not applied against the aggregations, but on the non-aggregated columns. The problem here is in how you are describing what the HAVING clause applies to. The HAVING clause always applies to aggregated fields, which is all remaining columns post-aggregation. You are trying to show / say that the HAVING clause is not being applied ...


13

Would you believe... SELECT col1, MIN(col2), MAX(col2), MIN(col3), MAX(col3) FROM table1 GROUP BY col1; ...? each row includes the first value of col2 and col3 for each unique value of col. That assertion is not exactly true. That may be what you're seeing, but do not assume this to be meaningful and do not write code based on this observation. ...


12

You are not showing the query you are using to obtain the results without diff. I'm assuming it is something like this: SELECT min = MIN(Value), max = MAX(Value), avg = AVG(Value), -- or, if Value is an int, like this, perhaps: -- AVG(CAST(Value AS decimal(10,2)) Date = DATEADD(HOUR, DATEDIFF(HOUR, 0, Date), 0) FROM atable ...


12

I created the table big_table according to your schema create table big_table ( updatetime datetime not null, name char(14) not null, TheData float, primary key(Name,updatetime) ) I then filled the table with 50,000 rows with this code: DECLARE @ROWNUM as bigint = 1 WHILE(1=1) BEGIN set @rownum = @ROWNUM + 1 insert into big_table ...


12

Thank you for SQLfiddle and sample data! I wish more questions started this way. If you want all members regardless of whether they have an entry for that date, you want a LEFT OUTER JOIN. You were very close with this version however a little trick with outer joins is that if you add a filter to the outer table in the WHERE clause, you turn an outer join ...


12

First answer uses a CTE to select max(group_value) and then join with the table. with maxgv as ( select element, max(group_value) maxg from x group by element ) select x.element, x.group_value, x.value from maxgv inner join x on x.element = maxgv.element and x.group_value = maxgv.maxg ; This one uses RANK() function: with grp ...


12

You can use GROUP BY with the GROUPING SETS () modifier: select name, city, sum(salary) total_salary from Employee group by grouping sets ((city, name), (city)) ; Example of use from Microsoft Technet: Using GROUP BY with ROLLUP, CUBE, and GROUPING SETS


11

SELECT type, GROUP_CONCAT( CASE WHEN info = 'yes' THEN name ELSE NULL END ORDER BY id ASC SEPARATOR ' ') AS list_with_info, GROUP_CONCAT( CASE WHEN info = 'no' THEN name ELSE NULL END ORDER BY id ASC SEPARATOR ' ') AS list_without_info FROM table1 GROUP BY type ; Tested at SQL-Fiddle: test-1 ...


11

If you have a limited number of values that you want to convert into columns, then this can easily be implemented using an aggregate function with a CASE expression: select user_id, sum(case when message_type = 'private' then 1 else 0 end) private, sum(case when message_type = 'public' then 1 else 0 end) public from yourtable group by user_id See SQL ...


11

group is a reserved word (and by is another reserved word) - it's not GROUP BY that is reserved. Because it is a reserved word, it cannot be used directly as an identifier. To use a reserved word or a name with "illegal" characters (such as a space) for an identifier, you need to quote the identifier. ALTER TABLE test RENAME COLUMN sum TO "group"; Note ...


11

As a MySQL DBA, I sadly admit that MySQL can be rather cavalier in its SQL processing. One of the most infamous feats of this is its GROUP BY behavior. As example, Aaron Bertrand answered the post Why do we use Group by 1 and Group by 1,2,3 in SQL query? where he described MySQL's GROUP BY as cowboy who-knows-what-will-happen grouping. I just had to agree. ...


11

I found it in the SQL 2011 spec... If the <select list> “*” is simply contained in a <table subquery> that is immediately contained in an <exists predicate>, then the <select list> is equivalent to a <value expression> that is an arbitrary <literal>. This confirms that by * not being equivalent to an arbitrary literal ...


11

I'm going to use a simpler example where it is clear to see what the expected results are. CREATE TABLE Queen ( FirstName VARCHAR(7), Surname VARCHAR(7) ); INSERT INTO Queen (FirstName, Surname) VALUES ('Brian', 'May'), ('Freddie', 'Mercury'), ('John', 'Deacon'), ('Roger', 'Taylor') ; Query 1 SELECT ...


11

UNION excludes duplicate rows. You want to use UNION ALL in this example: SELECT id, SUM(num) as sum FROM ( SELECT 1 AS id, 2 AS num UNION ALL SELECT 1, 2 /*!*/) AS a GROUP BY id Results: id sum ----------- ----------- 1 4


10

I infer that your data looks like this: Person Table ╔══════════╦═══════╦════════╗ ║ PersonID ║ Name ║ Gender ║ ╠══════════╬═══════╬════════╣ ║ 1 ║ John ║ M ║ ║ 2 ║ Vicky ║ F ║ ║ 3 ║ Bob ║ M ║ ╚══════════╩═══════╩════════╝ Job Table ╔══════════╦═════════════╦════════════╗ ║ PersonID ║ JobName ║ HireDate ║ ╠═══...


10

A simple and fast variant: SELECT min(number) AS first_number, count(*) AS ct_free FROM ( SELECT *, number - row_number() OVER (PARTITION BY id_set ORDER BY number) AS grp FROM tbl WHERE status = 'FREE' ) x GROUP BY grp HAVING count(*) >= 3 -- minimum length of sequence only goes here ORDER BY grp LIMIT 1; Requires a gapless ...


Only top voted, non community-wiki answers of a minimum length are eligible