SQL Server - select distinct rows and sum of duplicates - sql-server

I am facing 1 prob in implementing business solution. Any help would be much appreciated.
There is 1 table with 3 columns.
Table Employee
(
Id, Name, Salary
)
Values -
(1,John,10000),
(2,Rey, 15000),
(3,John,20000)
Expected Output -
It should fetch only distinct employees and for duplicate records of employee, it should fetch sum of salary.
So, output should be like this -
(1,john,30000),
(2,Rey,15000)
Please help

Check the basic sintaxis for GROUP BY
SELECT MIN(ID), Name, SUM(Salary)
FROM Employee
GROUP BY Name
The interesting part here is aggregation functions doesnt need to be at the end. As are usually show in the examples

Related

Use pivot to get sum of each column using a join

I have two tables in SQL and I want to first join them and then use a pivot and get sum for each column by date.
For example:
Table Name Sales:
I have another Table called Manufacturer:
I want to join these tables and sum up the totals for Offer_Price, Sale_Price and Discount. I want to get the results date wise for each Manufacturer.
I wrote a query:
*/
Select Manufacturer_Name ,
date,
Offer_Price,
Sale_Price,
Discount
From
(
Select M.name, S.Date, S.Offer_Price, S.Sale_Price , S.Discount
from dbo.sales S
Inner join dbo.Manufacturer M on S.m_id = M.M_id
) as PivotData
Pivot (Sum(Offer_Price) , sum (Sale_Price), sum (Discount)
For date in ([2020-03-22], [2020-03-21], [2020-03-20])) as pivoting /*
But I get an error:
Incorrect syntax near ','.
This error is for the row where I am adding up the columns.
I am trying to learn pivot but I am stuck here. Can someone help?
Please note that I made up the data above, these are not the actual columns and tables but they are similar.
The results I want are like:
For Manufacturer Vivo and date 03/22/2020 it should add up and show offer price as 20,000, sale_Price as 19900, discount as 100 in a single row.

How to construct an SQL query for finding which company has the most employees?

I have the following tables and I would like to find the company which has the most workers. I am fairly new to sql and I would like some help on constructing the query. Any briefing would be appreciated on which keywords to use or how to begin with writing the query. I would like to
“Find the company that has the most workers.”
worker(worker_name, city, street)
work for(worker_name, company_name, salary)
company(company_name, city)
manages( worker_name, manage_name)
this will get you the company with the most employees in it.
select top 1 company_name,
count(*) as nbr_of_employees
from work-for
group by company_name
order by 2 desc
For more detailed answer please add sample data to your question and expected result.
how it works:
the group by company_name will group all records with the same company_name togheter. Because of that the count(*) will give you the number of records in work-for for each group. (thus all workers for each company)
the order by 2 desc will make sure that the company-name with the most employees is on top of the lists
Finally, the top 1 in the select will only return the first record in that list

SQL SERVER - Retrieve Last Entered Data

I've searched for long time for getting last entered data in a table. But I got same answer.
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID DESC;
My scenario is, how to get last data if that Customers table is having CustomerName column only? No other columns such as ID or createdDate I entered four names in following order.
James
Arun
Suresh
Bryen
Now I want to select last entered CustomerName, i.e., Bryen. How can I get it..?
If the table is not properly designed (IDENTITY, TIMESTAMP, identifier generated using SEQUENCE etc.), INSERT order is not kept by SQL Server. So, "last" record is meaningless without some criteria to use for ordering.
One possible workaround is if, by chance, records in this table are linked to some other table records (FKs, 1:1 or 1:n connection) and that table has a timestamp or something similar and you can deduct insertion order.
More details about "ordering without criteria" can be found here and here.
; with cte_new as (
select *,row_number() over(order by(select 1000)) as new from tablename
)
select * from cte_new where new=4

Basic T-SQL COUNT

I'm new to T-SQL and this question is T-SQL Count 101.
I'm studying T-SQL with this site http://sqlmag.com/t-sql/t-sql-101-lesson-4 but I can't figure out Which part of coding says WHERE(column_name) to execute 'COUNT' if it makes sense? In other words, how does this COUNT know what to count? It just says COUNT everything as Reviews from MovieReview table.....
SELECT MovieName,
LEFT(REPLICATE('* ',AVG(Stars)),10)
AS 'Stars',
COUNT(*) AS 'Reviews'
FROM MovieReview
GROUP BY MovieName
HAVING COUNT(*) >= 4
ORDER BY Stars
Result:
The TABLE name is MovieReview that contains the ratings that the five employees have given to movies they’ve watched in their spare time. This table contains four columns: EmployeeID, Genre, MovieName, and Stars. The Stars field specifies the movie’s rating, where 1 star is the worst rating and 5 is the best rating.
I understand below coding because it specified WHERE. Count everything as '...' From Employee table Where salary is less than 3000.
SELECT COUNT(*)
AS 'Impoverished'
FROM Employee
WHERE Salary < 30000
I need to learn creating reports from Data Warehouse. I learned SQL but most of sites use T-SQL when creating reports, I don't know why.
Thanks in advance.
count(*) counts the number of rows that match the where clause if a where clause is given, per distinct combination of the group by columns if a group by column is given.
Except for the behavior noted in the previous sentence, count(*) ignores the values in those rows.

How do i find the total number of records created on a given day using T-SQL?

I need to find out the total number of records that were created on a given day.
e.g.
ID CreatedDate
1 17/07/2009
2 12/07/2009
3 17/07/2009
4 05/07/2009
5 12/07/2009
6 17/07/2009
Output:
3 Records were created on 17/07/2009
2 Records were created on 12/07/2009
1 Record was created on 05/07/2009
EDIT
Upon testing the second suggestion made by Chris Roberts of including the formatting in the SQL i get this error:
Syntax error converting the varchar value ' Records were created on ' to a column of data type int.
Does anyone know how to rework the solution so that it works?
You should be able to get the data you're after with the following SQL...
SELECT COUNT(ID), CreatedDate
FROM MyTable
GROUP BY CreatedDate
Or - if you want to do the formatting in the SQL, too...
SELECT CONVERT(varchar, COUNT(ID)) + ' Records were created on ' + CONVERT(varchar, CreatedDate)
FROM MyTable
GROUP BY CreatedDate
Good luck!
Is the column actually a timestamp? In which case you will need to apply a function to remove the time component, e.g.:
SELECT COUNT(*), date(CreatedDate) FROM MyTable GROUP BY date(CreatedDate)
I don't know what the function is in T-SQL, it's date() in MySQL and trunc() in Oracle. You may even have to do a to_string and remove the end of the string and group by that if you lack this.
Hope this helps.
select count(*), CreatedDate from table group by CreatedDate order by count(*) DESC

Resources