Trying to create a measure in PowerBi - formatting

I'm trying to create a measure that would be something like;
If transportation is Cars and they are Toyota and Honda and Ford and if dates are between 01/01/2019 and 10/01/2019 then the total should be 54000. This is an example. I'm not sure if I need to separate the data from the master list in order to get the information I need.

Assuming this is as simple as it sounds and you have some existing measure to give you the "total" of 54,000 (if not, use SUMX or something instead), it should be something like this:
Measure1 =
CALCULATE (
[total],
Table1[transportation] IN {"Ford", "Honda", "Toyota"},
Table1[date] >= FORMAT ( "1/1/2019", "Short Date" ),
Table1[date] <= FORMAT ( "10/1/2019", "Short Date" )
)

Related

Max partition by DAX measure equivalent?

In DAX/Power BI, I wondering if it is possible to create an aggregate calculation on a subset of data within a dataset.
I have a listing of customer scores for a period of time, e.g.
date, customer, score
-----------------------
1.1.17, A, 12
2.1.17, A, 16
4.1.17, B, 10
5.1.17, B, 14
I would like to identify to Max date per customer eg.
date, customer, score, max date per client
-------------------------------------------
1.1.17, A, 12, 2.1.17
2.1.17, A, 11, 2.1.17
4.1.17, B, 10, 5.1.17
5.1.17, B, 14, 5.1.17
The SQL equivalent would something like-
MAX(date) OVER (PARTITION BY customer).
In DAX/Power BI I realise that a calculated column can be used in combination with EARLIER but this will not be suitable because the calculated column is not responsive to filtering from a slicer. I.e I would like to find the MAX date per client as illustrated above for a filtered date range controlled from a slicer and not for the full data set which is what a calculated column does. Is such a measure possible?
You will want a measure like this:
Max Date by Customer =
CALCULATE(
MAX(Table1[Date]),
FILTER(
ALLSELECTED(Table1),
Table1[customer] = MAX(Table1[customer])
)
)
The ALLSELECTED removes the local filter context while preserving any slicer filtering.
The filter Table1[customer] = MAX(Table1[customer]) is basically the measure equivalent of Table1[customer] = EARLIER(Table1[customer]) in a calculated column.
You can use subquery :
select *, (select max(t1.date)
from table t1
where t1.customer = t.customer
) as max_date_per_client
from table t;

SSRS Report Multi Parameters (start date,end date, MeterId, Displayby)

In my SSRS report there are 4 parameters StartDate, EndDate, MeterId, & DisplayBy
Start Date: datetime datatype
EndDate : datetime datatype
MeterId : is a drop down list and this will populate based on SQL query
DisplayBy: is a drop down list and this has the following values (Hour,day,Month & year)
The Database that stores hourly values for Meters, the following are the DB table columns: (MeterId,ReadingDate,Hours,Quantity,Price)
When I select the startdate, end date and the meter Id and display i want to show report based on the startdate & enddate and then by display values.
If the display is hour, the we got display all the 24 hour values for the MeterId,Quantity, Price for the date range.
If the display is day, we got display total quantity and total price for the MeterId for that date range.
If the display is Month, we got display total quantity and total price for the MeterId for that date range.
If the display is Year, we got display total quantity and total price for the MeterId for that date range. Say for example If i select start date as 1-1-2016 and end date as 12-31-2016. My result should show 12 rows for each month with their total Quantity, Total price for that particular MeterID.
my DB table stores all the hourly values i know how to show the values on screen if the user selects the display dropdown as hour. But, dont know how to show the result for day/month/year or how to group it. Do I need to use "case" statement and if so what should i need to give on display parameters.
Please suggest your idea...
Row Grouping:
SELECT I.CustomerName, I.ReadingDate, I.IntegratedHour, I.IntegratedUsage, I.IntegratedGeneration, DATEPART(dd, I.ReadingDate) AS [Reading Day], DATEPART(mm,
I.ReadingDate) AS [Reading Month], DATEPART(yyyy, I.ReadingDate) AS [Reading Year]
FROM IntegratedHour_MV90 AS I INNER JOIN
CustRptMeterExtract AS CT ON CT.CustomerName = I.CustomerName
WHERE (I.ReadingDate >= #StartDate) AND (I.ReadingDate <= #EndDate) AND (I.CustomerName IN (#FacilityName))
Expected Result:
SSRS Current Output: Doesnot match
Depending on your layout you could set row grouping to an expression something like this
=SWITCH
(
Parameters!ReportBy.Value=1, Fields!Hour.Value,
Parameters!ReportBy.Value=2, Fields!Day.Value,
Parameters!ReportBy.Value=3, Fields!Month.Value,
Parameters!ReportBy.Value=4, Fields!Year.Value,
True, 0)
This assumes you have already have the hours/days/months/years in your dataset, if not then you would have to replace the field references with expressions to return the relevant month etc.
Based on what I can see above you'll need to add a grouping level for Customer before the group expression. Also, you Quantity expression should be a sum something like this
=SUM(FIelds!IntegratedGeneration.Value)
You may still have a problem though. I'm assuming Price is a unit price, so it does not make sense to sum that too. To get round this, you should calculate the LineValue (Qty * Price) in your dataset then change the price expression to be something like
=(SUM(FIelds!LineValue.Value)/SUM(Fields!IntegratedGeneratio‌​n.Value))
and this will give you the average price.
However, this may be slow and personally I would do the work in your dataset. Again assuming you have the months, years in your table then you could do something like this.
--DECLARE #ReportBy int = 1 -- uncomment for testing
select
MeterID, Price
, CASE #ReportBy
WHEN 1 THEN [Month]
WHEN 2 THEN [Year]
ELSE NULL
END AS GroupByColumn
INTO #t
from dbo.MyDataTable
SELECT
GroupByColumn
, SUM(Price) as Price
FROM #t
Group BY GroupByColumn
Order by GroupByColumn
This assumes your report parameter is called ReportBy, if not just swap the name out.

Create SQL view column from result set

I'm new to SQL and attempting to revise a Create View script to add a new column from a select statement result set I've googled this quite a bit but haven't seen a good example.
Here's the select statement:
select lease_id, year(posting_date) as years1, SUM(amount) as Annual
from la_tbl_lease_projection
group by year(posting_date), lease_id
order by lease_id
The complicating factor is this. The Annual column in the result set is the Annual sum of expenses for a lease_id. However, in the view I'm adding the column to, expenses are listed monthly. So lease_id 100001 has 12 lines in 2010, 2011, etc. I want the view to have the new column show the Annual amount on each of the 12 monthly line items. The new Annual column should be to the right of the amount column and each line should contain the sum of the amount column for that year. e.g.:
Lease_id Posting_Date Amount Annual
100001 2010-01-01 $25 $300
100001 2010-02-01 $25 $300
etc...............
The view I'm adding to is a reasonably complex join and union from multiple tables. Instead of creating a new table for my result set, I'd like to access it using a stored procedure, unless there's a better option. MSDN says temp tables and table variables don't work in views so that's not an option.
I think this can be done by something like "when years1 = years1 AND lease_id = lease_id then [Annual] = resultset total, but can't seem to visualize it. Thanks in advance for your input.
Since you were looking at MSDN, I'm assuming SQL Server for this answer;
To get a yearly column that's a by year sum of amounts, you can use SUM() OVER ();
SELECT *, SUM(Amount) OVER (PARTITION BY YEAR(Posting_Date)) Yearly
FROM la_tbl_lease_projection;
An SQLfiddle to test with.
I think a derived table would do the trick for you something like:
select blah, blah2, blah3, ..., a.annual
from
<Long complicated set of joins>
join
(select lease_id, year(posting_date) as years1, SUM(amount) as Annual
from la_tbl_lease_projection
group by year(posting_date), lease_id
order by lease_id) a
on sometable.lease_id = a.lease_id and year(sometable .posting_date) = a.years1
Where <complex where conditions>

SQL query assign days to periods based on end date

I have a table that has a list of dates from now till 2015.
eg.
Date
11/1/2013
12/1/2013
13/1/2013
...
25/1/2013
I have a separate table this holds report dates.
cutoff_ date purpose
11/1/2013 Mid Month Report
25/1/2013 Month End Report
So I need to assign a the dates between 11/1/2013 and 25/1/2013 all to 25/1/2013 whats the best way to go about this?
Can I do it in a simple SQL query?
The DB is currently in Access if that makes a difference
Use DMin to retrieve the minimum cutoff_date which is greater than or equal to [Date].
SELECT
[Date],
DMin("cutoff_date", "report_dates",
"[cutoff_date] >= " & Format([Date], "\#yyyy-m-d\#")) AS report_date
FROM first_table;
There can be advantages to using subqueries, for example, you can use a parameter, which can be assigned in code, got from a form, or simply typed in. This example selects only those records that have a date that matches the cutoff_date purpose entered in the prompt [please enter purpose].
SELECT DISTINCT dates.day,
(SELECT TOP 1 cutoff_date
FROM report_dates
WHERE cutoff_date >= dates.day
AND purpose = [please enter purpose]
ORDER BY cutoff_date) AS CutOff
FROM dates
WHERE (SELECT TOP 1 cutoff_date
FROM report_dates
WHERE cutoff_date >= dates.day
AND purpose = [please enter purpose]
ORDER BY cutoff_date) IS NOT NULL;

Finding StartDate,EndDate from overriding StartDates

I have two tables with the following (simplified) structures:
table "Factors" which holds data about purchased goods' factors and has these columns:
FactorSerial, PurchaseDate, PurchasedGood
table "Prices" which holds goods prices on different dates
Serial, GoodCode, EvaluationDate, Price
A price is valid until a new row with the same Code but different date is added and thus updates its value
Now, I want to create a table which adds the price to the table 1 according to purchase date.
So if we have:
PurchaseDate PurchasedGood
-----------------------------
05/20/2011 A111
and:
GoodCode EvaluationDate Price
--------------------------------
A111 02/01/2011 100
...
A111 04/01/2011 110
...
A111 06/01/2011 120
the result would be
PurchaseDate PurchasedGood Price
-----------------------------------
05/20/2011 A111 110
Preferred method is creating the view Prices1 as
Serial GoodCode StartDate EndDate Price
and then joining Factors with this view by
PurchasedDate between StartDate AND EndDate
Can anybody show me how to create view1 (or obtaining the final result with any other method)? Thanks in advance!
P.S. sorry for my bad English!
I want to create a table which adds the price to the table 1 according to purchase date.
Here is a query that returns such data. The syntax is pretty standard SQL, I believe, but this was tested on SQL Server (looks like you may be using PostgreSQL with your "serial" naming).
select a.FactorSerial, a.PurchasedGood, a.PurchaseDate
, (select max(Price) from Prices where GoodCode = a.PurchasedGood and EvaluationDate = a.EvaluationDate) as Price
from (
select f.FactorSerial, f.PurchasedGood, f.PurchaseDate, max(p.EvaluationDate) as EvaluationDate
from Factors as f
join Prices as p on f.PurchasedGood = p.GoodCode
where f.PurchaseDate >= p.EvaluationDate
group by f.FactorSerial, f.PurchasedGood, f.PurchaseDate
) as a
This query assumes that there are no Purchases before a Price existed.
Also, considering:
Preferred method is creating the view Prices1 as
Serial GoodCode StartDate EndDate Price
and then joining Factors with this view by
PurchasedDate between StartDate AND EndDate
between is inclusive. Using this method that you've described, you would get duplicates if a PurchaseDate lies on the EndDate of one row and the StartDate of another.