Take first row after group in SQL Server [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
Does anyone know how to take always the first row after group by in SQL Server? Look on the screenshot for better explanation:
Result after select:
+------+---------+------+
| NAME | CAR | AGE |
+------+---------+------+
| Alex | BMW | 5 |
+------+---------+------+
| Alex | Audi | 2 |
+------+---------+------+
| Tom | VW | 10 |
+------+---------+------+
| Tom | Renault | 4 |
+------+---------+------+
| Tom | Peugeot | 2 |
+------+---------+------+
Expected result after group by:
+------+-----+
| NAME | CAR |
+------+-----+
| Alex | BMW |
+------+-----+
| Tom | VW |
+------+-----+

You can try to use the ROW_NUMBER() window function with PARTITION_BY clause. This function assigns a sequential integer to each row within the partition of a result set. The row number starts with 1 for the first row in each partition.
After that, you can use the where clause to select rows that have row numbers as 1.
You can follow this article for a better understanding.
Below is just an example (As I don't know how your query works):
select *
from
(
SELECT
ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) row_num,
*
from(
-- your main group by query
)
)
where row_num=1

you should be able to get the top 1 record for each person using the below query, let me know if this works for you.
SELECT * FROM car_owners GROUP BY person_name;
let me know if you want to order the records in alphabetical order ASC or DESC and then GROUP BY them
Thank You
enter image description here

Related

postgresql: How to sort a postgresql table in a permanent way? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I am a having a table with columns id, name, and date_time. I need to sort the table according to the date_time column.
Actual data in database:
id | name | date_time
----+----------------+----------------------------
1 | The flat | 2022-07-06 09:17:07.990454
2 | The Smetha | 2022-08-08 09:17:07.990454
3 | Kingston | 2022-07-02 04:17:08.990454
4 | The Oxford U | 2022-08-08 04:14:08.990454
5 | Studio Element | 2022-08-08 01:14:08.990454
6 | The Davils | 2022-08-02 04:14:08.990454
7 | Latitude | 2022-09-08 04:14:08.990454
8 | Star Eight | 2022-08-08 06:14:08.990454
9 | Cottages one | 2022-07-08 05:14:08.990454
I want to sort the date_time column in ASC order. Can I use the RANK() function?
Ex:
id | name | date_time
----+----------------+----------------------------
1 | Kingston | 2022-07-02 04:17:08.990454
2 | The flat | 2022-07-06 09:17:07.990454
3 | Cottages one | 2022-07-08 05:14:08.990454
4 | The Davils | 2022-08-02 04:14:08.990454
5 | Studio Element | 2022-08-08 01:14:08.990454
6 | The Oxford U | 2022-08-08 04:14:08.990454
7 | Star Eight | 2022-08-08 06:14:08.990454
8 | The Smetha | 2022-08-08 09:17:07.990454
9 | Latitude | 2022-09-08 04:14:08.990454
I want to sort the date_time column in ASC order. But here we should not use [...] ORDER BY
That's like saying "I want so get the sum of A and B, but we should not use A+B"
ORDER BY is the way to sort tables in SQL. Tables in relational databases (as explained in comments) are not excel sheets, they are a set of records, and they lack an implicit order.
Like others have said that the way to be sure that it will sort in a specific order is by specifying order by column, but in your case I did find something that does order by date_time without saying explicitly, but it's not guaranteed, and you need to add a new column, so if you really need to sort it without using order by this can be a work around.
select row_number() over(partition by date_time), id, name, date_time
from table
See db<>fiddle.
The reason why this would work is because it looks on each date and time in date_time column, and returns you groups of each date_time, so it really sorts it per date_time. So if you need to do the sort without using order by, you can use row_number(). But the real way to sort is by using order by.

how to limit selection with select [duplicate]

This question already has answers here:
LIMIT 10..20 in SQL Server
(15 answers)
Closed 2 years ago.
I tried using limit order to get a result like
student_id | name | major
1 | kate | bio
2 | david | chem
3 | jake | math
instead of
student_id | name | major
1 | kate | bio
2 | david | chem
3 | jake | math
4 | ... | ...
5 | ... | ...
which means 3 results instead of 5 but i got a syntax error and couldn't find solutions. any suggestions?
SQL Server uses SELECT TOP or OFFSET/FETCH to limit rows. So, your query should look like:
select top (3) t.*
from t
order by student_id;
Note that the ORDER BY is important if you care about which rows you want. SQL tables represent unordered sets. You need an ORDER BY if you care about the ordering.

MS-Access SQL DISTINCT GROUP BY

I am currently trying to SELECT the DISTINCT FirstNames in a GROUP, using Microsoft Access 2010.
The simplified relevant columns of my table looks like this:
+----+-------------+-----------+
| ID | GroupNumber | FirstName |
+----+-------------+-----------+
| 1 | 1 | Peter |
| 2 | 1 | Bob |
| 3 | 1 | Peter |
| 4 | 2 | Rosemary |
| 5 | 2 | Jamie |
| 6 | 3 | Peter |
+----+-------------+-----------+
My actual table contains two columns to which I want to apply this process (separately), but I should be able to simply repeat the process for the other column. The column group number is a simplification, my table actually groups all rows in a ten day interval together, but I've already solved that problem.
And I would like it to return this:
+-------------+------------+
| GroupNumber | FirstNames |
+-------------+------------+
| 1 | Peter |
| 1 | Bob |
| 2 | Rosemary |
| 2 | Jamie |
| 3 | Peter |
+-------------+------------+
This means that I want all Distinct FirstNames for each Group.
A regular DISTINCT would ignore group boundaries and only mention Peter once. All aggregate functions reduce my output to only one value or don't work on strings at all. Access also doesn't support SELECTing columns that are not aggregates or in the GROUP BY statement.
All other answers I've found either want an aggregate, are not applicable to MS Access or are solved by working around the data in ways not applicable to my case. (Standardized languages are a nice thing, aren't they?)
My current (invalid) query looks like this:
SELECT GroupNumber,
DISTINCT FirstNames -- This is illegal, distinct applies to all
-- columns and doesn't respect groups.
FROM Example AS b
-- Complicated stuff to make the groups
GROUP BY GroupNumber;
This query is a one time thing and is used to analyze a 58000 row excel spreadsheet exported from another Database (not my fault), so optimizing for runtime is not necessary.
I would like to achieve this purely through SQL and without VBA if at all possible.
This should work:
SELECT DISTINCT GroupNumber, FirstNames
FROM Example AS b
A solution for this problem would be group by the columns GroupNumber and FirstNames at the same time. The query is presented below:
Select GroupNumber, FirstNames
From input
Group By GroupNumber, FirstNames
(Standardized languages are a nice thing, aren't they?)

SQL create view with sum query [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have following registration table
| EMP_ID | START_DATE | END_DATE | PNUM |
| 1 | 2014-10-20 | 2014-10-25| 10 |
| 2 | 2014-10-20 | 2014-10-30| 30 |
And i want following result in view
| START_DATE | END_DATE | TOTALNUM |
| 2014-10-20 | 2014-10-25| 40 |
| 2014-10-20 | 2014-10-30| 40 |
And i have tried to create view with sum query but no success .
create view EMP
as
select START_DATE ,END_DATE,(select SUM(PNUM) from s) TOTALNUM
from s
group by [START_DATE],END_DATE
Assuming that there is no grouping but just selecting every row and show it's start & end date and the sum of PNUM of all the rows:
SELECT START_DATE, END_DATE, SUM(PNUM) FROM TableX

Need help on SQL query (self join) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a table like this
MAIN ID CONTENT SUB ID
ABCD ONE 888
ABCD TWO 888
which i would like the query result to be like this
MAIN ID SUB ID CONTENT1 CONTENT2
ABCD 888 ONE TWO
You can use the PIVOT function:
select
*
from (
select
[main id],
[sub id],
[content],
'content' + cast(
row_number() over (partition by [main id],[sub id] order by content)
as varchar(5)) as contentIX
from
table1
) T
pivot (max(Content) for contentIX in (content1,content2)) as content
The subquery first generates a field name for each result to pivot, content1, content2, etc. that looks like this:
| MAIN ID | SUB ID | CONTENT | CONTENTIX |
|---------|--------|---------|-----------|
| ABCD | 888 | ONE | content1 |
| ABCD | 888 | TWO | content2 |
Then the outer query performs a pivot over the CONTENTIX column to get the final result:
| MAIN ID | SUB ID | CONTENT1 | CONTENT2 |
|---------|--------|----------|----------|
| ABCD | 888 | ONE | TWO |
Demo: http://www.sqlfiddle.com/#!6/095bb/11