SQL sum all rows by id - sql

I am trying to learn SQL queries and have this scenario where I have this table:
Table1
ID | Name | Hour
----------------
1 | Mark | 2
2 | ken | 1.5
3 | jake | 3
1 | Mark | 1.8
2 | ken | 1
Expected result
ID | Name | Hour
----------------
1 | Mark | 3.8
2 | ken | 2.5
3 | jake | 3
I have tried to use the sum() function but I get an error.
My query:
Select ID, Name, Sum(Hour)
From Table1
Where ID = ID
Response:
Kindly use Group by clause whenever the Aggregate functions (min(),max(),sum(),count(),...etc.,) and columns are used together.
Non aggregated columns present in SELECT columns should be used in GROUP BY clause.

For using aggregate function you need to use Group By like this:
Select ID, Name , Sum(Hour) AS Hour From Table1
Group By ID, Name
Order By ID

Related

How can I select all rows from a table where the combination of two columns is distinct on each row (SQL Server)?

I have a table like this:
UsersPositions
id Name PositionId UserId Code
---------------------------------------------------------------
1 | Produce | 1 | 1 | A
2 | Fruits | 2 | 2 | C
3 | Grocery | 1 | 3 | B
4 | Produce | 1 | 1 | A
5 | Fruits | 2 | 2 | C
6 | Dairy | 4 | 8 | F
How can I select all results from this table, but remove duplicate entries in which the combination of PositionId and UserId is the same?
Where essentially, the result of the select statement would be this:
id Name PositionId UserId Code
---------------------------------------------------------------
1 | Produce | 1 | 1 | A
2 | Fruits | 2 | 2 | C
3 | Grocery | 1 | 3 | B
6 | Dairy | 4 | 8 | F
I want to filter using DISTINCT or GROUP BY on PositionId and UserId. I know I can easily get a list of unique values using:
SELECT UserId, PositionId
FROM UsersPositions
GROUP BY UserId, PositionId
But I also want to grab the other columns. From what I've looked on SO, it seems like I would want to make this a subquery and join it into another query. But how can I do that?
I saw something like this: Finding duplicate values in a SQL table, but it doesn't account for other columns. This post Selecting Distinct combinations. has a few answers with INNER JOIN, but it doesn't work correctly when I try that.
I thought this would be a quick google search for me, but I can't seem to find anything that works on SQL Server. What's the best way to handle this kind of query?
From your sample data, all four columns other than id are the same. If that is the case, you can use aggregation:
select max(id), Name, PositionId, UserId, Code
from t
group by Name, PositionId, UserId, Code;
This looks like a perfect case to use a CTE with window funtions.
;with cte
as (select id, [name], positionID, UserID, Code, row_number() over(partition by positionID, UserID order by id) rn
from tbl)
select * from cte where rn=1

Count redundant for each value in a column in SQL server

If I have the following table in a SQL Server 2019 database as follows:
|id | name | count |
+-----+--------+--------+
| 1 | rose | 1 |
| 2 | peter | 1 |
| 3 | ann | 1 |
| 4 | rose | 2 |
| 5 | ann | 2 |
| 6 | ann | 3 |
| 7 | mike | 1 |
I would like to find out if an inserted name already exists in the column "name" and how many times and right a count next to it as shown in "count" column. For example when ann was inserted the second time I put count value bext to it which is 2, and ann was inserted the third time I put 3 next to it.
How to do that using SQL?
Thank you
Here is one approach using the insert ... select syntax:
insert into mytable (name, cnt)
select v.name, (select count(*) + 1 from mytable t where t.name = v.name)
from (values (#name)) v(name)
The value to insert is given as #name in derived table values(). Then we use a subquery to count how many such names already exist in the table.
I would suggest that you calculate this information when you query the table, rather than when you insert rows:
select t.*,
row_number() over (partition by name order by id) as count
from t;
The value will always be correct -- even when the data is updated or rows are deleted.
Select Name, Count(*)
From Table
Group By Name

how to sum multiple rows with same id in SQL Server

Lets say I have following table:
id | name | no
--------------
1 | A | 10
1 | A | 20
1 | A | 40
2 | B | 20
2 | B | 20
And I want to perform a select query in SQL server which sums the value of "no" field which have same id.
Result should look like this,
id | name | no
--------------
1 | A | 70
2 | B | 40
Simple GROUP BY and SUM should work.
SELECT ID, NAME, SUM([NO])
FROM Your_TableName
GROUP BY ID, NAME;
Use SUM and GROUP BY
SELECT ID,NAME, SUM(NO) AS TOTAL_NO FROM TBL_NAME GROUP BY ID, NAME
SELECT *, SUM(no) AS no From TABLE_NAME GROUP BY name
This will return the same table by summing up the no column of the same name column.

Rows that have same value in a column, sum all values in another column and display 1 row

Example Table user:
ID | USER_ID | SCORE |
1 | 555 | 50 |
2 | 555 | 10 |
3 | 555 | 20 |
4 | 123 | 5 |
5 | 123 | 5 |
6 | 999 | 30 |
The result set should be like
ID | USER_ID | SCORE | COUNT |
1 | 555 | 80 | 3 |
2 | 123 | 10 | 2 |
3 | 999 | 30 | 1 |
Is it possible to generate a sql that can return the table above, so far I can only count the rows where certain user_id appear, but don't know how to sum and show for every user ?
You've included a column called "ID" in both the source data and desired results, but I'm going to assume that these ID values are not related and simply represent the row or line number - otherwise the question doesn't make sense.
In which case, you can simply use:
SELECT
USER_ID,
SUM(SCORE) AS SCORE,
COUNT(USER_ID) AS COUNT
FROM
<Table>
GROUP BY
USER_ID
If you really want to generate the ID column as well, then how you do this depends on the database platform being used. For example on Oracle you could use the ROWNUM pseudocolumn, on SQL Server you will need to use ROW_NUMBER() function (which also works for Oracle).
SELECT ID
,sum(SCORE)
,count(USER_ID)
FROM Table
GROUP BY
ID
I think COUNT is the number of scores per user_id, if so, then your sql request should be :
SELECT
ID,
USER_ID,
SUM(SCORE)AS SCORE,
COUNT(SCORE)AS COUNT
FROM
TABLE
GROUP BY
USER_ID

SQL : Getting duplicate rows along with other variables

I am working on Terradata SQL. I would like to get the duplicate fields with their count and other variables as well. I can only find ways to get the count, but not exactly the variables as well.
Available input
+---------+----------+----------------------+
| id | name | Date |
+---------+----------+----------------------+
| 1 | abc | 21.03.2015 |
| 1 | def | 22.04.2015 |
| 2 | ajk | 22.03.2015 |
| 3 | ghi | 23.03.2015 |
| 3 | ghi | 23.03.2015 |
Expected output :
+---------+----------+----------------------+
| id | name | count | // Other fields
+---------+----------+----------------------+
| 1 | abc | 2 |
| 1 | def | 2 |
| 2 | ajk | 1 |
| 3 | ghi | 2 |
| 3 | ghi | 2 |
What am I looking for :
I am looking for all duplicate rows, where duplication is decided by ID and to retrieve the duplicate rows as well.
All I have till now is :
SELECT
id, name, other-variables, COUNT(*)
FROM
Table_NAME
GROUP BY
id, name
HAVING
COUNT(*) > 1
This is not showing correct data. Thank you.
You could use a window aggregate function, like this:
SELECT *
FROM (
SELECT id, name, other-variables,
COUNT(*) OVER (PARTITION BY id) AS duplicates
FROM users
) AS sub
WHERE duplicates > 1
Using a teradata extension to ISO SQL syntax, you can simplify the above to:
SELECT id, name, other-variables,
COUNT(*) OVER (PARTITION BY id) AS duplicates
FROM users
QUALIFY duplicates > 1
As an alternative to the accepted and perfectly correct answer, you can use:
SELECT {all your required 'variables' (they are not variables, but attributes)}
, cnt.Count_Dups
FROM Table_NAME TN
INNER JOIN (
SELECT id
, COUNT(1) Count_Dups
GROUP BY id
HAVING COUNT(1) > 1 -- If you want only duplicates
) cnt
ON cnt.id = TN.id
edit: According to your edit, duplicates are on id only. Edited my query accordingly.
try this,
SELECT
id, COUNT(id)
FROM
Table_NAME
GROUP BY
id
HAVING
COUNT(id) > 1