SQL Server 2008 R2- Query to get total sales and qty sold by month - sql

I have 2 tables STOCK and ITEMS,
I am trying to get a report showing how total items purchased (ITEMS table- items.quanto), total sales for items(ITEMS table- I assume (items.quanto*items.it_unlist) with description(STOCK table- stock.desc1) by month (ITEMS table-items.odr_date) with classification (which is a field in the STOCK table- stock.assoc).
The owner wants this info for each month for 2011, 2012, and YTD 2013
so total qty sold for item with total sales of that item by month 2011, 2012, 2013 YTD
This is my query
select items.item, items.quanto, SUM(items.QUANTO*items.it_unlist) as [total cost], stock.desc1, items.it_sdate from items
inner join
stock
on
stock.number = items.item
where IT_SDATE between '2011-01-01 00:00:00.0' and '2011-12-31 00:00:00.0'
group by items.item, items.quanto, stock.desc1, items.it_sdate
order by IT_SDATE
I was hoping to get each item totaled sales and qty by month but this is what I figured out on my own…lol
any help is appreciated.

select
item,
right(convert(varchar(8), it_sdate, 3), 5) theMonth,
sum(quanto) totalQuantity,
sum(quanto * it_unlist) totalSales,
max(stock.desc1) descr,
max(stock.assoc) assoc
from
items inner join stock on
items.item = stock.number
where
it_sdate > '2011-01-01'
group by
item,
right(convert(varchar(8), it_sdate, 3), 5)
order by
item,
theMonth
http://sqlfiddle.com/#!3/246d3/18/0

if the item column of the items table is primary key, then you can’t display the each and every item number when you are trying to display the total sales and qty.
And also, the IT_DATE column consists of only one date per month in the table, then only the below query is possible, if not we need to write other query.
if not, you can select.
select i.quanto, sum(QUANTO * it_unlist) as [total list],
s.desc1, i.it_sdate from items i inner join stock s on (s.number = i.item)
where IT_SDATE > 2011-01-01
group by i.it_sdate order by IT_SDATE;

Related

SSRS set year variables per record

I need help to create a code to have it display years specified.
User defines years to report: Year1 Year2 Year3
ProductID Year1 data
Year2 data
Year3 data
where even if year 2 has no data like below
ProductID Year1 data
Year2
Year3 data
My current code will show all data that fit the criteria, but will not show Year2 due to no data.
My current code is
select
sales.ProductID, Sales.Trans_Year, Sum(salesQTY) as QTY
from
(select ProductID, Year(Trans_dt) as Trans_Year, salesQTY
from salestable) sales
group by
sales.ProductID, Sales.Trans_Year
My code is inefficient but I did the select twice so that it would group the year on transdate, if any new to make it better would much appreciated.
Hoping to get help to have the following result.
ProductID Year1 QTY
ProductID Year2
ProductID Year3 QTY
Thank you
You can select the years from your table and cross join them to the products to get a matrix of all years and products. The CROSS JOIN will make a record for each year for each product - regardless if the product was sold in that year.
Then LEFT JOIN your sales total. Using a LEFT JOIN will allow the year and product ID from the SALES_YEAR and SALES subqueries to show even if there's none of a product sold in that year.
SELECT PRODUCTS.ProductID, YEARS.SALES_YEAR, SALES.TOTAL_SALES
FROM (
SELECT ProductID
FROM salestable
GROUP BY ProductID
) AS PRODUCTS
CROSS JOIN (
SELECT YEAR(Trans_dt) AS SALES_YEAR
FROM salestable
WHERE YEAR(Trans_dt) IN #YEARS
) AS YEARS
LEFT JOIN (
SELECT ProductID, Year(Trans_dt) as Trans_Year, SUM(salesQTY) AS TOTAL_SALES
FROM salestable
GROUP BY Year(Trans_dt)
) SALES ON SALES.Trans_Year = YEARS.SALES_YEAR AND SALES.ProductID = PRODUCTS.ProductID
Note that this assumes that you sold something every year selected. If the user enter 1905 for the year and there's no data for 1905, that year wouldn't appear. That shouldn't really be an issue though.

simple sql query highest sales

There are 2 tables - Products and Sales
Products
prod_id
prod_nm
Sales
prod_id
cust_id
sls_dt
sls_amt
Write a query selecting ALL the products. For each product show total of sales amounts in the past 30 days or 0 if not sold in 30 day withoug using subqueries.
Since different RDBMS have different date functions, you can filter by date using the following pseudo code - sls_dt > now() - 30.
Im new to sql and im trying it like this as i found this online.
Select prod_id, prod_nm from(
Select sls_amt
From Sales) as t
Where t.rank = 1
However, this isnt' working. Any help is appreciated
Try below:
select p.prod_id,
p.prod_nm,
sum(s.sls_amt)
from products p
left outer join Sales s on p.prod_id = s.prod_id
and s.sls_dt > now() - 30
group by p.prod_id,
p.prod_nm;

Weighted-Avg Access Query

Background: I have the following table with clothing brand names, the count of the brand name sold, the revenue the brand name has brought in, and an avg per unit sold of that brand name.
Quantity Brand Revenue Rev_Per_Brand
1820 CMD $13,519.50 $7.43
791 ATL $8,997.00 $11.37
335 WHBM $4,988.00 $14.89
320 CH $4,593.50 $14.35
233 AT $3,207.50 $13.77
Objective: Calculate the weighted average revenue by quantity sold of brands.
What I Have Now:
SELECT
COUNT(*) AS [Quantity],
Sales.Description AS Brand,
FORMAT(SUM(Sales.Amt),"Currency") AS Revenue,
Format(SUM(Sales.Amt)/COUNT(*), "Currency") AS Rev_Per_Brand,
SUM(Sales.Amt)*(COUNT(*)/SUM(COUNT(*))) AS [wAvg_Rev_Per_Brand]
FROM Sales
WHERE Sales.Date > DateAdd("m",-1,NOW())
AND "This query lists brands that have sold in the past 1 month from today's date and returns the revenue received from them" <> ""
GROUP BY Sales.Description
ORDER BY COUNT(*) DESC;
Problem: I am receiving the cannot have aggregate function in expression error, and I am guessing it is probably in the SUM(COUNT(*)) part above.
I am simply trying to do the count of the specific brand over the total count (sum) of all brands sold. Can anyone tell me what I am doing wrong?
Thank you and I really appreciate any help in advance.
You can not double aggregate i.e SUM(COUNT(*)) you've got to have that count in a separate subquery,
change your query to:
SELECT
COUNT(*) AS [Quantity],
Sales.Description AS Brand,
FORMAT(SUM(Sales.Amt),"Currency") AS Revenue,
Format(SUM(Sales.Amt)/COUNT(*), "Currency") AS Rev_Per_Brand,
SUM(Sales.Amt)*(COUNT(*)/(SELECT Count(*) FROM sales)) AS [wAvg_Rev_Per_Brand]
FROM Sales
WHERE Sales.Date > DateAdd("m",-1,NOW())
AND "This query lists brands that have sold in the past 1 month from today's date and returns the revenue received from them" <> ""
GROUP BY Sales.Description
ORDER BY COUNT(*) DESC;

Revenue year by year SQL Server query

I have the following query which provides me with the item and item details, values, rate and quantity across each location.
I am trying to get the yearly revenue based on the Start and End Date. Example, if the chosen date was 2013-2015. The final result will create 3 columns one for 2013 revenue, one for 2014 revenue and one for 2015 revenue.
I am a newbie and still not an expert in writing queries, but here is what I have currently:
SELECT
department,
item,
itemdesc,
qty1,
qty2,
rate_1,
rate_2,
SUM(mm.days*mm.rate*mm.qty)
FROM
items it
LEFT JOIN
(SELECT
i.days, i.rate, i.days, ii.todate, ii.itemid
FROM
invoiceofitems ii
JOIN
invoices i on i.id = ii.id
WHERE
ii.todate BETWEEN #StartDate and #EndDate) mm ON mm.itemid = it.itemid
GROUP BY
department,
item,
itemdesc,
qty1, qty2,
rate_1, rate_2
ORDER BY
item
However, this does not provide me with a year to year aggregation of invoice revenue that I require.
I know this is possible to achieve via iterating through this. But how would I accomplish this and where would I start on this?
Would I need to know the start and end date of each year and iterate through that and then add a counter to the year until year= EndDate?
I'm extremely confused. Help would be appreciated.
I hope that PIVOT and YEAR help you to solve this problem (some columns are omitted):
;WITH SRC(department,item, ... , rate_2, yr, calculation) AS
(SELECT it.department, it.item, ..., it.rate_2, YEAR(ii.todate) as yr,
(i.days * i.rate *i.qty) as calculation
FROM items it
LEFT JOIN invoiceofitems ii ON ii.itemid = it.itemid
JOIN invoices i ON i.id = ii.id)
SELECT department,item, ..., [2013],[2014],[2015]
FROM SRC
PIVOT
(SUM(calculation) FOR yr IN ([2013],[2014],[2015])) PVT
The YEAR function returns only 'year' part of your date and makes grouping easier. PIVOT just rotates grouped data from rows to columns.

sql query to calculate monthly growth percentage

I need to build a query with 4 columns (sql 2005).
Column1: Product
Column2: Units sold
Column3: Growth from previous month (in %)
Column4: Growth from same month last year (in %)
In my table the year and months have custom integer values. For example, the most current month is 146 - but also the table has a year (eg 2011) column and month (eg 7) column.
Is it possible to get this done in one query or do i need to start employing temp tables etc??
Appreciate any help.
thanks,
KS
KS,
To do this on the fly, you could use subqueries.
SELECT product, this_month.units_sold,
(this_month.sales-last_month.sales)*100/last_month.sales,
(this_month.sales-last_year.sales)*100/last_year.sales
FROM (SELECT product, SUM(units_sold) AS units_sold, SUM(sales) AS sales
FROM product WHERE month = 146 GROUP BY product) AS this_month,
(SELECT product, SUM(units_sold) AS units_sold, SUM(sales) AS sales
FROM product WHERE month = 145 GROUP BY product) AS last_month,
(SELECT product, SUM(units_sold) AS units_sold, SUM(sales) AS sales
FROM product WHERE month = 134 GROUP BY product) AS this_year
WHERE this_month.product = last_month.product
AND this_month.product = last_year.product
If there's a case where a product was sold in one month but not another month, you will have to do a left join and check for null values, especially if last_month.sales or last_year.sales is 0.
I hope I got them all:
SELECT
Current_Month.product_name, units_sold_current_month,
units_sold_last_month * 100 / units_sold_current_month prc_last_month,
units_sold_last_year * 100 / units_sold_current_month prc_last_year
FROM
(SELECT product_id, product_name, sum(units_sold) units_sold_current_month FROM MyTable WHERE YEAR = 2011 AND MONTH = 7) Current_Month
JOIN
(SELECT product_id, product_name, sum(units_sold) units_sold_last_month FROM MyTable WHERE YEAR = 2011 AND MONTH = 6) Last_Month
ON Current_Month.product_id = Last_Month.product_id
JOIN
(SELECT product_id, product_name, sum(units_sold) units_sold_last_year FROM MyTable WHERE YEAR = 2010 AND MONTH = 7) Last_Year
ON Current_Month.product_id = Last_Year.product_id
I am slightly guessing as the structure of the table provided is the result table, right? You will need to do self-join on month-to-previous-month basis:
SELECT <growth computation here>
FROM SALES s1 LEFT JOIN SALES s2 ON (s1.month = s2.month-1) -- last month join
LEFT JOIN SALES s3 ON (s1.month = s3.month - 12) -- lat year join
where <growth computation here> looks like
((s1.sales - s2.sales)/s2.sales * 100),
((s1.sales - s3.sales)/s3.sales * 100)
I use LEFT JOIN for months that have no previous months. Change your join conditions based on actual relations in month/year columns.