Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Sum sales for current month Expand / Collapse
Author
Message
Posted Tuesday, October 30, 2012 6:00 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Tuesday, December 9, 2014 7:37 AM
Points: 15, Visits: 127
Hi All,

I'm trying to sum the sales where the date parameter will automatically reference the current day/ month, which I have created (see below query). But I'm having trouble adding an extra line where the sum says, sum the products for the current month (EffectiveStartDateTime), but where the Insertdatetime is less than the current month.

I have enclosed an excel spreadsheet of what I am trying to Achieve.

Any help / advice would be very appreciated



Select top 100

[P].[ProductName] as [Product]
,CAST(ISNULL(SUM(CASE WHEN DATEDIFF(d, GETDATE() - 1, [BT].[EffectiveStartDateTime]) = 0 THEN [BTFB].[Amount] END), 0) AS money) AS [DailySales]
,CAST(ISNULL(SUM(CASE WHEN DATEDIFF(m, GETDATE() - 1, [BT].[EffectiveStartDateTime]) = 0 THEN [BTFB].[Amount] END), 0) AS money) AS [CurrentMonthSales]

FROM
[Product] AS [P]
INNER JOIN [dbo].[BusinessTransaction] AS [BT] ON [P].[ProductID] = [BT].[ProductID]
INNER JOIN [dbo].[BusinessTransactionFinancialBreakdown] AS [BTFB] ON [BT].[BusinessTransactionID] = [BTFB].[BusinessTransactionID]

WHERE
[BTFB].[FinancialFieldID] = 26
AND [BT].[BusinessTransactionTypeID] = 1

GROUP BY
[P].[ProductName]


  Post Attachments 
examplesqlcount.xlsx (10 views, 10.76 KB)
Post #1378711
Posted Tuesday, October 30, 2012 8:02 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Today @ 3:05 PM
Points: 13,320, Visits: 12,804
I am sure that what you posted is very clear for you. Unfortunately we don't know your project or data and we can't see you screen. If you can post ddl (create table scripts), sample data (insert statements) and desired output based on your sample data we can help. Take a look at the first link in my signature for best practices when posting questions.

You might also take a look at this article about dates. http://www.sqlservercentral.com/blogs/lynnpettis/2009/03/25/some-common-date-routines/


_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1378789
Posted Tuesday, October 30, 2012 12:12 PM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Friday, December 12, 2014 8:24 PM
Points: 1,945, Visits: 3,173
I'm trying to sum the sales where the date parameter will automatically reference the current month and current day, which I have created (see below query). But I'm having trouble adding an extra line where the sum says, sum the products for the current month (effective_start_timestamp), but where the insert timestamp is less than the current month.


Where is the DDL?

Your model of data is a spreadsheet. Both SQL and spreadsheets are both declarative languages. But they are very different. SQL is a data retrieval and storage tool; spreadsheets are computational.

You have framed your question from the spreadsheet approach. This does not work. Latin and Czech are inflectional languages, but you cannot use Czech grammar in Latin.

This is a good post for me because I usually see procedural language programming and have to “un-learn” that mindset when I teach.

You also have violations of ISO_11179 rules, etc. We do not use the old 1970's Sybase MONEY data types for two reasons; it has math errors (Google it) and it would put display formatting in the database (like a spreadsheet does). We also have the ANSI Standard CURRENT_TIMESTAMP instead of the old 1970's Sybase getdate().

Do you really have only one Product as you said? Since we work with sets, we would use a plural or collective name. There is no such thing as a “type_id” in RDBMS; you can have a “<something>_type”
or a “<something>_id” but not a hybrid that serves two totally different purposes. The term “financial_field_id” is scary; what is it? It sounds like a physical location in a record or a cell in a spreadsheet not the attribute of an entity.

Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML. The report period table gives a name to a range of dates that is common to the entire enterprise.

CREATE TABLE Report_Periods
(report_name VARCHAR(30) NOT NULL PRIMARY KEY,
report_start_date DATE NOT NULL,
report_end_date DATE NOT NULL,
CONSTRAINT date_ordering
CHECK (report_start_date <= report_end_date),
etc);

These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantage is that it will sort with the ISO-8601 data format required by Standard SQL when you pass it to the presentation layer.

Since you did not bother with minimal netiquette and give us DDL and clear specs, I can only give you a skeleton. Assume a table of daily transactions:

SELECT D.product_id, R.report_name,
SUM(sale_amt) AS sales_amt_tot
FROM Report_Periods AS R, Daily_Sales AS D
WHERE D.sale_date
BETWEEN R.report_start_date AND R.report_end_date
AND R.report_name = @in_report_month -– use yyyy-mm-00
GROUP BY D.product_id;

Maybe you can figure out how to make this work for you.


Books in Celko Series for Morgan-Kaufmann Publishing
Analytics and OLAP in SQL
Data and Databases: Concepts in Practice
Data, Measurements and Standards in SQL
SQL for Smarties
SQL Programming Style
SQL Puzzles and Answers
Thinking in Sets
Trees and Hierarchies in SQL
Post #1378942
Posted Wednesday, November 7, 2012 1:35 AM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Tuesday, October 28, 2014 6:04 AM
Points: 1,127, Visits: 1,599
Attaching an Excel sheet is not called providing readily consumable sample data. Please check the link in my signature and post sample data as shown in the link. This time i'll do it for you so that other Forum members can use it and provide you with a solution:

--Creating Table 

Create table Ex
(Product NVarchar(10),
InsertDateTime DateTime,
EffectiveDateTime DateTime,
Value Float )


--Inserting Sample Data

Insert into Ex
Select 'Apples', '1/9/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/9/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/9/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/10/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/10/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/10/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/10/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/10/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/10/2012 5:03', '1/10/2012 5:03', 1.00
Union ALL
Select 'Apples', '1/10/2012 5:03', '1/10/2012 5:03', 1.00


--Query for your Requirement

Select a.Product, a.[SumEffectivedate(currentday)] ,b.[SumEffectivedate(currentmonth)], c.[Sum Effectivedate(currentmonth)where_Insertdatetime_less_than_current_month]
From
(Select Product, SUM(Value) As [SumEffectivedate(currentday)]
From Ex
Group By Product, DATEPART(DD, EffectiveDateTime) ) As a
JOIN
(Select Product, SUM(Value) As [SumEffectivedate(currentmonth)]
From Ex
Group By Product, DATEPART(MM, EffectiveDateTime) ) As b ON a.Product = b.Product
JOIN
(Select Product, SUM(Value) As [Sum Effectivedate(currentmonth)where_Insertdatetime_less_than_current_month]
From Ex
Where DATEDIFF(DD, EffectiveDateTime, InsertDateTime) < 0
Group By Product, DATEPART(MM, EffectiveDateTime) ) As c ON a.Product = c.Product



From what I understood from the Excel sheet you provided....I came up with the above query. If this does not help then please provide the complete query that you are using and then may be someone might come up with a better solution.


Vinu Vijayan

For better and faster solutions please check..."How to post data/code on a forum to get the best help" - Jeff Moden
Post #1381822
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse