DAX expression for ROW_NUMBER() PARTITION BY ORDER BY equivalent - sql

I have a SQL statement like this:
(ROW_NUMBER() OVER (PARTITION BY a.[market], [MEASURE_TYPE]
ORDER BY AM, REP, ORDER_KEY)) AS ORDER_KEY
I want to write a DAX to implement the above SQL statement.

This is not as simple in DAX as in SQL. Here is an example:
Order Key Within Partition =
VAR CurrentMarket = [Market]
VAR CurrentMeasureType = [MeasureType]
VAR CurrentAM = [AM]
VAR CurrentREP = [REP]
VAR CurrentOrderKey = [OrderKey]
VAR CurrentPartition = FILTER (
a, -- the table name
[Market] = CurrentMarket
&& [MeasureType] = CurrentMeasureType
)
RETURN SUMX (
CurrentPartition,
IF (
ISONORAFTER (
CurrentAM, [AM], ASC,
CurrentREP, [REP], ASC,
CurrentOrderKey, [OrderKey], ASC
),
1
)
)
EDIT: Power Query would be better to achieve this.
let
/* Steps so far */
Source = ...,
...
a = ...,
/* End of steps so far */
/* Add steps below to add Order Key Within Partition column */
Partitions = Table.Group(
a,
{"Market", "MeasureType"}, {"Partition", each _}
)[Partition],
AddedOrderKeys = List.Transform(
Partitions,
each Table.AddIndexColumn(
Table.Sort(_, {"AM", "REP", "OrderKey"}),
"Order Key Within Partition",
1
)
),
Result = Table.Combine(AddedOrderKeys)
in
Result

I contribute with an alternative solution to the RANKX. The answer containing the Power Query is the correct one because avoid using calculated columns.
Sales[Sequence by Customer] =
VAR CurrentDate = Sales[Date]
VAR CurrentTime = Sales[Time]
RETURN COUNTROWS (
    FILTER (
        CALCULATETABLE (
            Sales,
            ALLEXCEPT ( Sales, Sales[Customer] )
        ),
        Sales[Date] < CurrentDate
          || ( Sales[Date] = CurrentDate
               && Sales[Time] <= CurrentTime )
    )
)
Source

Related

Covert SQL to Linq Query

I am doing my final year's project, I am new to linq as well. I have an SQL statement which i want to convert it to linq. I am currently using .net core.
I will greatly appreciate any help ,
WITH
cte_company (CompanyID, CompanyName, CompanyNumber, IncorporatedDate, TOTAL_YEARS) AS
(
SELECT
CompanyID,
CompanyName,
CompanyNumber,
IncorporatedDate,
DATEDIFF(YEAR, IncorporatedDate, CURRENT_TIMESTAMP) AS TOTAL_YEARS
FROM tbl_Company
)
SELECT
cte_company.CompanyID,
CompanyName,
CompanyNumber,
IncorporatedDate,
TOTAL_YEARS,
CASE
WHEN TOTAL_YEARS > 1 THEN (SELECT
DATEADD(MONTH, 9, MAX(TaxReturnDate))
FROM tbl_Tax
WHERE cte_company.CompanyID = tbl_Tax.CompanyID)
ELSE DATEADD(MONTH, 21, IncorporatedDate)
END AS TaxDate
FROM cte_company
I tried :
var result = (from comp in this.AccountDB.TblCompanies
where comp.CompanyStatus == true && comp.UserName == username
join tax in this.AccountDB.TblTaxes
on comp.CompanyId equals tax.CompanyId
orderby tax.TaxReturnDate descending
select new CompanyTaxInfo
{
CompanyName = comp.CompanyName,
CompanyID = comp.CompanyId,
CompanyNumber = comp.CompanyNumber,
})
.ToList();
As far as I can tell, the value read from tbl_tax is constant, which means it can be reduced to this:
var taxReturnDate = tbl_tax.Max(tx=>tx.TaxReturnDate).AddMonths(9);
var result = from c in tbl_Company
let TotalYears = (DateTime.Now - c.IncorporatedDate).Days / 365
select new
{
CompanyID = c.CompanyID,
c.CompanyName,
c.CompanyNumber,
c.IncorporatedDate,
TotalYears,
TaxDate = TotalYears > 1 ? taxReturnDate : c.IncorporatedDate.AddMonth(9)
}
You could still use your SQL with EF and still get the same result
for example if you create a stored procedure for your SQL
you could call it as the following
var result = await dbContext.<Your-Result-set>.FromSqlInterpolated(#$"[dbo].[Your-Procedure-Name]
{your-parameter1}
,{your-parameterN}
").ToListAsync();

How can convert SQL to lambda or LINQ

How can I convert below SQL to lambda or LINQ?
with cte
as (select * from test1
union all
select * from test2)
select * from cte
union all
select sum(columnA),sum(columnB),sum(columnC) from cte
In Linq UNION ALL is .Concat(), so:
var cte = test1.Concat(test2);
var sums = new MyModel
{
columnA = cte.Sum(c => c.columnA),
columnB = cte.Sum(c => c.columnB),
columnC = cte.Sum(c => c.columnC),
}
return cte.Concat(IEnumerable.Repeat(sums, 1));
You must remember that test1 and test2 must be type MyModel and MyModel contains only columnA, columnB and columnC.
I put two tables together in one datagridvie but in the last row of datagridview I need the total for both tables in the country, I can do one row in total for one table and another row for the other table I also don't need it, like I can only have one line with the total of both tables.
DataContex db = new DataContex();
var query = (
from v1 in db.View1
where shf.Date >= dpDate.Value && shf.Date <= dpDate1.Value
select new
{
v1.Name,
v1.Date,
v1.Quality,
v1.Rat,
v1.Total
}
).Concat
(
from v2 in db.View2
where f.Date >= dpDate.Value && f.Date <= dpDate1.Value
select new
{
v2.Name,
v2.Date,
v2.Quality,
v2.Rat,
v2.Total
}
).Concat
(from View2 in
(from v2 in db.View2
where v2.Date >= dpDate.Value && sh.Date <= dpDate1.Value
select new
{
v2.Name,
v2.Date,
v2.Quality,
v2.Rate,
v2.Total
})
group v2 by new { v2.NRFA } into g
select new
{
Name = "Total:",
Date = dpDate1.Value,
Quality = (decimal?)g.Sum(p => p.Quality),
Rate = (decimal?)g.Sum(p => p.Rate),
Total = (decimal?)g.Sum(p => p.Total)
}
);
Blockquote

Conditional statements in PIG

I have below input in a text file and need to generate output in another file based on the logic.
Here is my input file:
customerid|Dateofsubscription|Customercode|CustomerType|CustomerText
1001|2017-05-23|455|CODE|SPRINT56
1001|2017-05-23|455|DESC|Unlimited Plan
1001|2017-05-23|455|DATE|2017-05-05
1002|2017-05-24|455|CODE|SPRINT56
1002|2017-05-24|455|DESC|Unlimited Plan
1002|2017-05-24|455|DATE|2017-05-06
Logic:
If Customercode = 455
if( CustomerType = "CODE" )
Val= CustomerText
if( CustomerType = "DESC" )
Description = CustomerText
if( CustomerType = "DATE" )
Date = CustomerText
Output:
customerid|Val|Description|Date
1001|SPRINT56|Unlimited Plan|2017-05-05
1002|SPRINT56|Unlimited Plan|2017-05-06
Could you please help me with this.
rawData = LOAD data;
filteredData = FILTER rawData BY (Customercode == 455);
--Extract and set Val/Description/Date based on CustomerText and 'null' otherwise
ExtractedData = FOREACH filteredData GENERATE
customerId,
(CustomerType == "CODE" ? CustomerText : null) AS Val,
(CustomerType == "DESC" ? CustomerText : null) AS Description,
(CustomerType == "DATE" ? CustomerText : null) AS Date;
groupedData = GROUP ExtractedData BY customerId;
--While taking MAX, all 'nulls' will be ignored
finalData = FOREACH groupedData GENERATE
group as CustomerId,
MAX($1.Val) AS Val,
MAX($1.Description) AS Description,
MAX($1.Date) AS Date;
DUMP finalData;
I have specified the core logic. Loading, formatting and storage should be straight-forward.
Filter the input where customercode=455,generate the required 2 columns,then group by customerid and then use BagToString
.
B = FILTER A BY Customercode == 455;
C = FOREACH B GENERATE $0 as CustomerId,$4 as CustomerText;
D = GROUP C BY CustomerId;
E = FOREACH D GENERATE group AS CustomerId, BagToString(C.CustomerText, '|'); -- Note:This will generate 1001,SPRINT56|Unlimited Plan|2017-05-05 so,you will have to concat the first field with '|' and then concat the resulting field with the second field which is already delimited by '|'.
F = FOREACH E GENERATE CONCAT(CONCAT($0,'|'),$1);
DUMP F;

How do i transform a HQL result to List<T> where T is a mapped class

I have this nhibernate query:
var q =
NHibernateSession.Current.CreateSQLQuery
(
#"SELECT LastestEvents.*
FROM (
SELECT DISTINCT SbQcontainer.Container
FROM HistoricEvents
SbQcontainer WHERE SbQcontainer.LineCompany_Id = :lineCompany) as Sbq
JOIN HistoricEvents as LastestEvents
ON LastestEvents.id = (
SELECT TOP(1) id
FROM HistoricEvents mi
WHERE mi.Container = Sbq.Container and mi.LineCompany_Id = :lineCompany
ORDER BY mi.Date DESC
)"
).SetResultTransformer(Transformers.AliasToBean(typeof(HistoricEvent)));
q.SetParameter("lineCompany",lineCompany.Id);
q.SetCacheable(false);
var results = q.List<HistoricEvent>().ToList();
It looks for the lastest events on each container for the given lineCompany, it works, but i dont know how to set this resultset to a list of T HistoricEvent, i try this line:
.SetResultTransformer(Transformers.AliasToBean(typeof(HistoricEvent)));
But throws NHibernate.PropertyNotFoundException:Could not find a setter for property 'Event_Id' in class 'HistoricEvent'.
Is there any way to do this?, or maybe doing this same query using the ICriteria API?
Thx in advance.
Assuming HistoricEvent is a mapped entity, the following should give you what you're looking for:
var q =
NHibernateSession.Current.CreateSQLQuery
(
#"SELECT LastestEvents.*
FROM (
SELECT DISTINCT SbQcontainer.Container
FROM HistoricEvents
SbQcontainer WHERE SbQcontainer.LineCompany_Id = :lineCompany) as Sbq
JOIN HistoricEvents as LastestEvents
ON LastestEvents.id = (
SELECT TOP(1) id
FROM HistoricEvents mi
WHERE mi.Container = Sbq.Container and mi.LineCompany_Id = :lineCompany
ORDER BY mi.Date DESC
)"
).AddEntity(typeof(HistoricEvent));
q.SetParameter("lineCompany",lineCompany.Id);
q.SetCacheable(false);
var results = q.List<HistoricEvent>().ToList();
See the relevant documentation for further details.

Need Linq translation for the following SQL Query

select colId,
colTaskType,
MaxID
from tblTaskType
join (
select tblCheckList.colTaskTypeID,
max(colItemNumber) MaxID
from tblCheckList
group by colTaskTypeID
) x on coltaskTypeID = tblTaskType.colID
Assuming you are using linq-to-sql and have the two tables in a datacontext.
The more or less exact translation would be:
var maxChecks = from checks in DataContext.tblChecklist
group checks by checks.colTaskTypeID into g
select new { colTaskTypeID, max = g.Group.Max(x => x.colItemNumber) };
var result = from t in DataContext.tblTaskType
join c in maxChecks on t.colTaskTypeID equals c.colTaskTypeID
select new { t.colId, t.colTaskTypeID, c.max };
But you could try:
var result = from t in DataContext.tblTaskType
select new {
t.colId,
t.colTaskTypeID,
Max = (from c in DataContext.tblChecklist
where c.colTaskTypeID == t.colTaskTypeID
select c.colItemNumber).Max() };