MSSQL Finding Total of a column and carry other data with it - sql-server

I have the following table to work with, which I can not change. I have to work with what I have.
Id (int auto int)
CustomerName (varchar)
CustomerNumber (int)
Date (date)
WeeklyAmount (int)
What I would like to do is grab all the data per customer and add all the weekly amounts for a specific year. Eventually I will want to compare two years together, but right now I am working on the data to sum up the weekly totals per CustomerNumber.
I am using:
Select
CustomerNumber, SUM (WeeklyAmount) as Total from
Customers.RECORDS GROUP BY CustomerNumber;
This works fine, however, I want to return the CustomerName as well. Eventually I will have to place in the SQL for getting specific years and compare them. However, I have to tackle this part first.

Assuming there is a 1-to-1 relationship between CustomerName and CustomerNumber:
Select
CustomerNumber, CustomerName, SUM (WeeklyAmount) as Total from
Customers.RECORDS GROUP BY CustomerNumber, CustomerName;
If the relationship is not 1-to-1, then I suppose you'd need to define what exactly represents a customer in the phrase grab all the data per customer.

Related

How to get sum of column from specific representatives orders?

I have a column called balance and another column called repnum. Repnum represents a representative who's taken care of customers. I've managed to grab the customers name, the specific representative i'm looking for (15), and I know I can grab the balance by taking out (sum(balance)) but what I want to do is get the sum of the balance column with only representative 15's orders. This is what I currently have thought up:
select customername, repnum, sum(balance) balance from customer where repnum = '15'
Add an over clause to the sum function to prevent the need for group by:
Select customername,
Repnum,
Sum(balance) over(partition by repnum) balance
From customer
Where repnum = 15
I think you can just add group by customername, repnum to the end of your query.

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

t sql sort by calculated column

I'm on T-SQL 2014 and try to order products by their price. Now here is the problem: the price is a calculated field. Eg. I have created a function which evaluates a number of pricing rules (maybe about 4 tables with each about 4,000,000 records combined with JOINs to fit to the current login) and returns the users price for the product. While this is OK if I just want to return the price for a limited number of products it is way to slow if I want to sort by this.
I was thinking about having an additional table like UserProductPrice which will get calculated in the background but this will obviously not always have the correct price in it as the rules etc. could change in between the calculation.
Any suggestion on how I could sort by the price would be most appreciated.
You could use the ROW_NUMBER() function and place this into a temp table:
SELECT
Product,
dbo.ufnPrice(Price) as Price,
ROW_NUMBER() OVER (PARTITION BY Product ORDER BY dbo.ufnPrice(Price) DESC) AS Ranking
INTO #Products
FROM dbo.Products
SELECT
Product,
Price,
FROM #Products
WHERE Ranking = 1
DROP TABLE #Products
Should give you what you need.

Creating a function to add a calculated column to a table in SQL Server based on a query

I have 2 database tables called Spend, and VendorSpend. The columns used in the Spend table are called VendorID, VendorName, RecordDate, and Charges. The VendorSpend table contains VendorID and VendorName but with distinct data (one record for each unique VendorID). I need a simple way to add a column to the VendorSpend table called Aug2015, this column will contain the SUM of each Vendor's charges within that month time period. It will be calculated based on this query:
Select Sum(Charges)
from Spend
where RecordDate >= '2015-08-01' and RecordDate <= '2015-08-31'
Keep in mind this will need to be called whenever new data is inserted into the Spend table and the VendorSpend table will need to update based on the new data. This will happen every month so actually a new column will need to be added and the data be calculated every month.
Any assistance is greatly appreciated.
Create a user-defined function that you pass a VendorID and Date to and which does your SELECT:
Select Sum(Charges)
from Spend
where VendorID=#VendorID
AND DATEDIFF(month, RecordDate, #Date) = 0
Now personally, I would stop right there and use the function to select your data at query time, rather than adding a new column to your table.
But treating your question as academic, you can create a computed column called [Aug2015] in VendorSpend that passes [VendorID] and '08/01/2015' to this function and it will contain the desired result.

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.

Resources