SSRS sort month by current month in order - tsql

I'm running sparkline reports and charts in SSRS have been nothing but a pain to work with for me. I'm trying to run a 1-year from today sparkline - the query groups the data by month, but I want it to sort descending by the most current date - so it would read 1-2014, 12/2013.. and back
SELECT DATEPART(month, Orders.OrderDate) AS month, COUNT(Orders.OrderID) AS Count, SUM(Orders.GrossSubtotal) AS GrossRevenue, SUM(Orders.Subtotal) AS Revenue,
SUM(Orders.OrderCost) AS Cost, SUM(Orders.Subtotal) - SUM(Orders.OrderCost) AS Margin, SUM(Orders.Subtotal) / COUNT(Orders.OrderID) AS averageOrder
FROM Orders LEFT OUTER JOIN
Campaigns ON Orders.CampaignCode = Campaigns.CampaignCode CROSS JOIN
PK_StatsCurrentDatesCMP
WHERE (CONVERT(date, Orders.OrderDate, 103) BETWEEN PK_StatsCurrentDatesCMP.[1_YearRoll] AND PK_StatsCurrentDatesCMP.EndDate) AND
(Orders.SuppressFromStats = 0) AND (Orders.Void = 0) AND (Orders.WholesaleOrder = 0)
GROUP BY DATEPART(month, Orders.OrderDate)
ORDER BY month DESC
right now with ordering by desc it just gives me 12,11,10...

I went through all that trouble to type it out and I guess the writing solved it-obvious, I just needed to
ORDER BY MAX(Orders.Orderdate)
hope this is useful to someone

Related

DAX Calculate Billing Days Between Two Variable Dates

I have a dimdate table that is represented below. I have each day flagged as BusinessDay Y/N. I also have a DimSalesRep table that has a daily goal for each rep. I want to be able to allow users to input a StartDt and EndDt with filters on the report and have a calculated column look at the business days between those dates. I can calculate daysbetween with defined dates but I am unsure how I would use DAX with variable dates that are applied through Report filters.
I should also note I am not sure how best to handle a startdt and enddt filter based of the column, TheDate
Cheers!
Reference your dimdate table twice
StartDate = 'dimdate'
EndDate = 'dimdate'
and use this measure:
Num BusinessDays =
CALCULATE(
COUNTROWS('dimdate'),
'dimdate'[BusinessDay] = "Y",
'dimdate'[Date] >= SELECTEDVALUE(StartDate[Date]),
'dimdate'[Date] <= SELECTEDVALUE(EndDate[Date])
)

Create a measure to return the maximum date about the order in a fact table. (SSAS Multidimensional)

I want to create a measure which return the maximum date about Orders but before the actual day
I will write an example :
My tables here
(In my table Calendar i have the year 2016,2017,2019, and in my Order table, i have an order for 2016 and 2019,
I want the last date order but before the actual day (18/05/2017), so i want the Date 01/01/2016).
I have 2 table, a dimension Calendar and a fact table Order.
I was thinking about the function filter, so i search how to use filter in
google, and all the solutions i found use 'With' and 'Select'.
(I can't use 'With' and 'Select' when i create a measure in SSAS multidimensional).
Hope i will see your advice.
Just like this similar case in adv cube?
[max order date] return the maximum date about [Internet Sales Amount]
with member [max order date] AS
tail(NONEMPTY([Date].[Date].[Date],[Measures].[Internet Sales Amount])).item(0).item(0).PROPERTIES( "name" )
select {[max order date] } on 0 from [Adventure Works]
if yes, then you can create a measure in your cube like this:
Create Member CurrentCube.[Measures].[max order date]
As tail(NONEMPTY([Date].[Date].[Date],[Measures].[Internet Sales
Amount])).item(0).item(0).PROPERTIES( "name" );
if only till current day, then(following is refer to adv cube, you need do some code changes per your cube):
Create Member CurrentCube.[max order date] AS
Tail
(
NonEmpty
(
{
Head([Date].[Date].[Date]).Item(0).Item(0)--the first day in your Date dim
:
StrToMember("[Date].[Date].&[" + Format(Now(),"yyyyMMdd") + "]")-- as of current day
}
,[Measures].[Internet Sales Amount]
)
).Item(0).Item(0).Properties("name")
IDE to Write, Analyze, Tuning, Debug MDX efficiently (www.mdx-helper.com)

Syntax for column values for same period of last year in SSRS report

I am generating a report where I SUM price and cost values per month. I would like to show the same defined time period - 1 year. I'm not clear how to nest this. Would I use a case when statement?
My terrible example.
select month, cost, price from table1 where (define months here in SSRS parameter filter)
I'd like to see:
select month, cost, price, lastyearcost, lastyearprice FROM table1 where (define months here in SSRS parameter filter)
I know that I should be using some variant of GETDATE() -1, but will this include the data range parameters passed when running the report? How do I select the column of cost apply the date filter and then get the result of cost for that period last year?
Hopefully that makes sense?
One way is to use DATEPART() with the correct nesting and pairing.
select
month,
cost,
price,
lastyearcost,
lastyearprice
FROM table1
where
--this is limiting the data to the year passed in, and the previous year
(datepart(year,DateColumn) = #YearParam or datepart(year,DateColumn) = #YearParam-1)
and
--this is limiting the months to the two parameters you pass in as integers
(datepart(month,DateColumn) >= #minMonthParam and datepart(month,DateColumn) <= #maxMonthParam)
TEST DATA
See the DEMO HERE
declare #table1 table (DateColumn date)
insert into #table1 (DateColumn)
values
('1/1/2016'),
('2/1/2016'),
('3/1/2016'),
('4/1/2016'),
('5/1/2016'),
('6/1/2016'),
('7/1/2016'),
('8/1/2016'),
('9/1/2016'),
('10/1/2016'),
('11/1/2016'),
('12/1/2016'),
('1/1/2017'),
('2/1/2017'),
('3/1/2017'),
('4/1/2017'),
('5/1/2017')
declare #YearParam int = 2017
declare #minMonthParam int = 2
declare #maxMonthParam int = 5
select
DateColumn
FROM #table1
where
(datepart(year,DateColumn) = #YearParam or datepart(year,DateColumn) = #YearParam-1)
and
(datepart(month,DateColumn) >= #minMonthParam and datepart(month,DateColumn) <= #maxMonthParam)

SQL Syntax for Date that exist in on year but not in Another

I'm trying to write a query that would give me the records of all members that have Order dates that exist in 2013 but not in 2014. When I write my query it gives me ALL of the 2013 records which still exist in 2014. I'm trying to get ONLY record that have order dates in 2013 and not in 2014. So it should show records which exist in 2013 and exclude records that do not exist in 2014. Please help as I'm really new to SQL.
Thank you very much.
Below is my query:
SELECT
OMFMC.BILL_MASTER_CUSTOMER_ID,
OMFMC.BILL_FIRST_NAME,
OMFMC.BILL_LAST_NAME,
CMI.NATIONAL_LEVEL2,
MIN(OMFMC.ORDER_DATE),
OMFMC.ORDER_DATE,
FT.PAYMENT_AMOUNT,
SUM(FT.PAYMENT_AMOUNT)as SUM
FROM
CUSTOMER CUSTOMER_IN_TRIBUTE_TO
RIGHT OUTER JOIN ORDER_FND_DETAIL OFD
ON (CUSTOMER_IN_TRIBUTE_TO.MASTER_CUSTOMER_ID=OFD.IN_TRIBUTE_TO_MAST_CUST
and CUSTOMER_IN_TRIBUTE_TO.SUB_CUSTOMER_ID=OFD.IN_TRIBUTE_TO_SUB_CUST)
RIGHT OUTER JOIN ORDER_MBR_FND_MTG_CUS_INFO_VW OMFMC
ON (OMFMC.ORDER_NO=OFD.ORDER_NO
and OMFMC.ORDER_LINE_NO = OFD.ORDER_LINE_NO )
LEFT OUTER JOIN CUS_CURRENT_MEMBERSHIP_INFO CMI
ON (CMI.MASTER_CUSTOMER_ID=OMFMC.BILL_MASTER_CUSTOMER_ID
and CMI.SUB_CUSTOMER_ID=OMFMC.BILL_SUB_CUSTOMER_ID)
LEFT OUTER JOIN FAR_TXN FT
ON (FT.ORDER_NO=OMFMC.ORDER_NO
and FT.ORDER_LINE_NO=OMFMC.ORDER_LINE_NO)
WHERE
OMFMC.ORDER_STATUS_CODE='A'
AND OMFMC.LINE_STATUS_CODE = 'A'
AND OMFMC.ORDER_STATUS_CODE = 'A'
AND OMFMC.LINE_STATUS_CODE = 'A'
AND OMFMC.ORDER_DATE BETWEEN '1/1/2013' and '12/31/2013'
AND OMFMC.ORDER_DATE Not BETWEEN '1/1/2014' and '12/31/2014'
AND OMFMC.BILL_CUSTOMER_CLASS_CODE NOT IN ( 'TEST_MBR','STAFF' )
AND FUND in ('FOSFN' , 'MFUND')
GROUP BY
OMFMC.BILL_MASTER_CUSTOMER_ID,
OMFMC.BILL_FIRST_NAME,
OMFMC.BILL_LAST_NAME,
OMFMC.BILL_LABEL_NAME,
OMFMC.BILL_PRIMARY_EMAIL_ADDRESS,
OMFMC.BILL_ADDRESS_1,
OMFMC.BILL_ADDRESS_2,
OMFMC.BILL_CITY,
OMFMC.BILL_STATE,
OMFMC.BILL_POSTAL_CODE,
CMI.NATIONAL_LEVEL2,
OMFMC.ORDER_DATE,
FT.PAYMENT_AMOUNT
HAVING SUM(FT.PAYMENT_AMOUNT) < 0
Order By BILL_MASTER_CUSTOMER_ID
In the order dates field, there are dates that have 2013, and 2014 dates. I want a my query to look at 2013 and 2014 order dates and ONLY pull out order dates that are in 2013. Not the records that have 2013 and 2014 dates. If they have an order in 2013 AND 2014 then I want to exclude those records. So for example:
enter code here
Bill_Member_ID..........Order_Date
123....................01/05/2013
123.................... 01/27/2013
123.................... 02/15/2014
123.................... 02/18/2014
456.................... 01/07/2013
789.................... 01/05/2013
789.................... 02/17/2014
992.................... 03/15/2013
So then I should get a return of
Bill_Member_ID..........Order_Date
456.................... 01/07/2013
992.................... 03/15/2013
Thank you so much
What you need is a simple subselect, and to feed its results into your outermost select to display the results.
What you are after is the list of Bill_Member_ID who have an order date between 2013-01-01 and 2013-12-31 (inclusive) but do not have an order dates in between 2014-01-01 and 2014-12-13. So, let's build our pseudo-code select. We do this inside out (starting at the innermost, and working our way to the outermost layer of the select).
First up, generate a list of Members who have orders in 2014. So that's
Select Bill_Member_ID
From Order_Table
WHERE Year( OrderDate ) = '2014';
We feed that as a condition to the next select. This next layer's job is to select all the Members who have an OrderDate in 2013, but not in 2014.
Select Bill_Member_ID
From Order_Table
WHERE Year( OrderDate ) = '2013' AND Bill_Member_ID Not In
(
Select Bill_Member_ID
From Order_Table
WHERE Year( OrderDate ) = '2014'
)
This yields your list of Bill_Member_ID who have orders in 2013, but not in 2014. Add the additional columns you need for your final select. Also, add in your other filtering conditions (ie, the not Test and not Staff) to narrow the results as needed.
That's really all you need to do to generate your list of sought customers. If you aren't using a database that does not supports just specifying the year, then you'll need to use the between dates to filter the where date field in range of condition.

SSRS/TSQL date formatting

Using the following sample query below in SSRS would return month as single number(1-12). What I want to is to display the date as is something like Jan 2000. How would I go about changing my code to be able to format from single number month to a MMM YYYY format? I tried the formatting in visual studio itself but it is currently returning as MMM YYYY.
select distinct count(*) as Count,
con.STATE,
month(con.sub_Date) as Month,
year(con.sub_Date) as Year
from contract con
group by con.STATE,month(con.sub_date),year(con.sub_date)
I strongly recommend that you perform the formatting of the date at the report level.
Return the date from your query as the first date of the desired period, but then set the format string for the placeholder/text box.
The reason to do this is so that sorting and data manipulation works as expected when the report is exported to Excel.
So I would use a query as:
SELECT DISTINCT
COUNT(*) AS Count ,
con.STATE ,
DATEADD(MONTH, DATEDIFF(MONTH, 0, con.sub_Date), 0) AS FirstOfMonth
FROM
contract con
GROUP BY
con.STATE ,
DATEADD(MONTH, DATEDIFF(MONTH, 0, con.sub_Date), 0)
and then use formatting codes in the report such as MMM, YYYY for display and break the date apart with =Month(fields!FirstOfMonth.Value) if you need the components for grouping. This will allow the users to pivot the data appropriately if needed.
Formatting of the dates is presentation logic, and should be kept out of SQL if possible.
You could add the following into the query to return the pre-formatted month/year as part of the report dataset - maybe easier than trying to reconstruct it at the report level:
select distinct count(*) as Count,
con.STATE,
month(con.sub_Date) as Month,
year(con.sub_Date) as Year,
left(datename(mm, sub_Date), 3) + ' ' + cast(year(sub_Date) as char(4)) as MonthYear
from contract con
group by con.STATE,
month(con.sub_date),
year(con.sub_date),
left(datename(mm, sub_Date), 3) + ' ' + cast(year(sub_Date) as char(4))
I usually prefer to use CONVERT to get partial dates, though I don't see any CONVERT date formats that would leave you cleanly with a MON YYYY output. However, format 106 will get you most of the way there. So combining that with RIGHT() will get you the date in the format you're looking for.
SELECT DISTINCT
COUNT(*) AS Count ,
[con].[STATE] ,
MONTH([con].[sub_Date]) AS Month ,
YEAR([con].[sub_Date]) AS Year ,
RIGHT(CONVERT(CHAR(11), [con].[sub_Date], 106), 8) AS MonthYear
FROM [dbo].[contract] AS con
GROUP BY [con].[STATE] ,
MONTH([con].[sub_Date]) ,
YEAR([con].[sub_Date]) ,
RIGHT(CONVERT(CHAR(11), [con].[sub_Date], 106), 8)