Author |
Topic |
skylimitsql
Starting Member
8 Posts |
Posted - 2014-08-10 : 11:28:17
|
Sample datadeclare @Product table(ProductID int, Product varchar(90), Cost decimal(18,2))insert into @Productselect 1, 'Product1', 50.50 union allselect 2, 'Product2', 150.50 union allselect 3, 'Product3', 250.50 select * from @Productdeclare @Sale table(SaleID int, SaleDate Datetime, Quantity int, ProductID int)insert into @Saleselect 1, '2014-01-01', 2, 1 union allselect 2, '2014-02-01', 3, 1 union allselect 3, '2014-03-01', 4, 2 union allselect 4, '2014-04-01', 5, 3Please can you help me with thisA query that will produce a report on the total sales per month over the period from the beginning of last year to date. Only amounts which total over £200 must be reported. I tried many possible things but not been able to write a correct SQLMany Thanks |
|
MichaelJSQL
Constraint Violating Yak Guru
252 Posts |
Posted - 2014-08-10 : 12:31:50
|
declare @Product table(ProductID int, Product varchar(90), Cost decimal(18,2))insert into @Productselect 1, 'Product1', 50.50 union allselect 2, 'Product2', 150.50 union allselect 3, 'Product3', 250.50 declare @Sale table(SaleID int, SaleDate Datetime, Quantity int, ProductID int)insert into @Saleselect 1, '2014-01-01', 2, 1 union allselect 2, '2014-02-01', 3, 1 union allselect 3, '2014-03-01', 4, 2 union allselect 4, '2014-04-01', 5, 3Declare @SalesDat datetime = '1/1/2014'-- base of your query to work with the needed resultsSELECT * ,s.Quantity*p.Cost TotalSale FROM @Sale S INNER JOIN @Product P ON S.productID = P.ProductIDWHERE S.Quantity * P.Cost >= 200AND SaleDate >= @SalesDatThis will sum by sales date --assuming all your sales are on the 1st - it will be by month: if not you will need to use DatePart to pull a month and perhaps year.SELECT s.SaleDate ,SUM(s.Quantity*p.Cost) TotalSale FROM @Sale S INNER JOIN @Product P ON S.productID = P.ProductIDWHERE S.Quantity * P.Cost >= 200AND SaleDate >= @SalesDatGroup by s.SaleDate |
|
|
skylimitsql
Starting Member
8 Posts |
Posted - 2014-08-10 : 13:02:28
|
Brilliant! Many Thanks |
|
|
|
|
|