case statement filter in MDX query - sql-server

I want to write the following T SQL query in MDX
Select count(bugs),priority from table
where
Case when priority =1 then startdate< dateadd(dd,-7,getdate())
when priority =2 then startdate< dateadd(dd,-14,getdate())
end
group by priority
Tried the following but not working
WITH MEMBER [Measures].CHECKING
AS
CASE [Item].[ startdate].CurrentMember
WHEN [Item].[ Priority].&[1] THEN [Item].[startdate]<DATEADD(DAY,-7,NOW())
WHEN [Item].[ Priority].&[2] THEN [Item].[startdate]<DATEADD(DAY,-14,NOW())
END
SELECT
NON EMPTY{[Measures].[Count], [Measures].CHECKING }ON COLUMNS
,NON EMPTY{([Item].[ Priority].[ Priority].ALLMEMBERS )}
I am new to MDX queries, any suggestions on how to approach this please..

Your CASE logic has a basic problem. The statement cannot result in a condition. It can only result in a value that you then compare to something else.
To take your tSQL example, I think it should read more like this:
Select count(bugs),priority from table
where
1 = Case when priority = 1 and startdate< dateadd(dd,-7,getdate()) Then 1
when priority = 2 and startdate< dateadd(dd,-14,getdate()) then 1
else 0 end
group by priority
A cleaner way to write this would be to skip the CASE altogether.
Select count(bugs),priority from table
where
(priority = 1 and startdate< dateadd(dd,-7,getdate()))
or
(priority = 2 and startdate< dateadd(dd,-14,getdate()))
group by priority

I am assuming the following:
Your startdate hierarchy is an attribute hierarchy, not a user hierarchy and
the current day is its last member.
Then the following MDX should deliver what you want:
SELECT
{ [Measures].[Count] }
ON COLUMNS
,
{ [Item].[ Priority].&[1], [Item].[ Priority].&[2] }
ON ROWS
FROM (
SELECT ({ [Item].[ Priority].&[1] }
*
([Item].[ startdate].[ startdate].Members
- Tail([Item].[ startdate].[ startdate].Members, 7)
)
)
+
({ [Item].[ Priority].&[2] }
*
([Item].[ startdate].[ startdate].Members
- Tail([Item].[ startdate].[ startdate].Members, 14)
)
)
ON COLUMNS
FROM [yourCube]
)
Your code [Item].[startdate]<DATEADD(DAY,-7,NOW()) does not work in MDX for several reasons: firstly, [Item].[startdate] is a hierarchy, and hence cannot be compared using <. Secondly, even if you would re-state it as [Item].[startdate].CurrentMember < DATEADD(DAY,-7,NOW()), you would have a member on the left side of the <, and a date , i. e. a value, on the right side. One of the important things to keep in mind with MDX are the different types of objects: Hierarchies, levels, members, tuples, sets. And all these are not values. You do not just have columns like in SQL.

Related

SQL Server - How to Use Merge Statement for Slowly Changing Dimension with More Than Two Conditions?

I am trying to implement Slowly Changing Dimension Type 2 through T-SQL but I can't figure out how to put a request to work.
Table columns: cpf, nome, telefone_update, endereco_insert
Basically the logic is: if the MATCH doesn't happen using cpf, then the record must be inserted; if the MATCH happens but only the telefone_update field has changed, there is no need to another record and I just want to UPDATE and override the values; if the MATCH happens but only the endereco_insert field has changed I want to add a new record and update the start and end dates.
What I have so far is:
insert into #dm_lucas_tst (
[cpf],
[nome],
[telefone_update],
[endereco_insert],
[dt_scd_start],
[dt_scd_end],
[nu_scd_version]
)
select [cpf],
[nome],
[telefone_update],
[endereco_insert],
cast(dateadd(month, datediff(month, 0, getdate()), 0) as date) as [dt_scd_start],
'2199-12-31' AS [dt_scd_end],
1 AS [nu_scd_version]
from (
merge edw.dim.dm_lucas_tst as Target
using edw.dim.stg_lucas_tst as Source
on Target.cpf = Source.cpf
when not matched by target
then
insert (
[cpf],
[nome],
[telefone_update],
[endereco_insert],
[dt_scd_start],
[dt_scd_end],
[nu_scd_version]
)
values (
Source.[cpf],
Source.[nome],
Source.[telefone_update],
Source.[endereco_insert],
cast(dateadd(month, datediff(month, 0, getdate()), 0) as date),
'2199-12-31',
1
)
when matched
and Source.telefone_update <> Target.telefone_update
and Target.dt_scd_end = '2199-12-31'
then
update set telefone_update = Source.telefone_update
output $ACTION ActionOut,
Source.[cpf],
Source.[nome],
Source.[telefone_update],
Source.[endereco_insert]
) AS MergeOut
where MergeOut.ActionOut = 'UPDATE';
But I don't think putting another WHEN MATCH AND ... will make that work.
Any suggestions?
Thanks in advance!
Accordingly to your description, I'm assuming that you need:
SCD Type 1 for column [telefone_update]
SCD Type 2 for column [endereco_insert]
I've used application SCD Merge Wizard to easily create described logic.
When I made tests for it - everything looks as expected, I guess.
I described the process on my blog - please have a look and tell me if that was exactly what you wanted?
https://sqlplayer.net/2018/01/scd-type-1-type-2-in-merge-statement/

Yet another subquery issue

Hello from an absolute beginner in SQL!
I have a field I want to populate based on another table. For this I have written this query, which fails with: Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
oK, here goes:
Update kre.CustomerOrderLineCopy
SET DepNo = (SELECT customerordercopy.DepNo
FROM kre.CustomerOrderCopy , kre.CustomerOrderLineCopy
WHERE CustomerOrderLineCopy.OrderCopyNo =kre.CustomerOrderCopy.OrderCopyNo)
WHERE CustomerOrderLineCopy.OrderCopyNo = (SELECT CustomerOrderCopy.OrderCopyNo
FROM kre.CustomerOrderCopy, kre.CustomerOrderLineCopy
WHERE kre.CustomerOrderLineCopy.OrderCopyNo = kre.CustomerOrderCopy.OrderCopyNo)
What I'm trying to do is to change DepNo in CustomerOrderLineCopy, with the value in DepNo in CustomerOrderCopy - based on the same OrderCopyNo in both tables.
I'm open for all suggestion.
Thanks,
ohalvors
If you just join the tables together the update is easier:
UPDATE A SET A.DepNo = B.DepNo
FROM kre.CustomerOrderLineCopy A
INNER JOIN kre.CustomerOrderCopy B ON A.OrderCopyNo = B.OrderCopyNo
The problem is that at least one of your sub queries return more than one value. Think about this:
tablePerson(name, age)
Adam, 11
Eva, 11
Sven 22
update tablePerson
set name = (select name from tablePerson where age = 11)
where name = 'Sven'
Which is equivalent to: set Sven's name to Adam and Eva. Which is not possible.
If you want to use sub queries, either make sure your sub queries can only return one value or force one value by using:
select top 1 xxx from ...
This may be enough to quieten it down:
Update kre.CustomerOrderLineCopy
SET DepNo = (SELECT customerordercopy.DepNo
FROM kre.CustomerOrderCopy --, kre.CustomerOrderLineCopy
WHERE CustomerOrderLineCopy.OrderCopyNo =kre.CustomerOrderCopy.OrderCopyNo)
WHERE CustomerOrderLineCopy.OrderCopyNo = (SELECT CustomerOrderCopy.OrderCopyNo
FROM kre.CustomerOrderCopy --, kre.CustomerOrderLineCopy
WHERE kre.CustomerOrderLineCopy.OrderCopyNo = kre.CustomerOrderCopy.OrderCopyNo)
(Where I've commented out kre.CustomerOrderLineCopy in the subqueries) That is, you were hopefully trying to correlate these subqueries with the outer table - not introduce another instance of kre.CustomerOrderLineCopy.
If you still get an error, then you still have multiple rows in kre.CustomerOrderCopy which have the same OrderCopyNo. If that's so, you need to give us (and SQL Server) the rules that you want to apply for how to select which row you want to use.
The danger of switching to the FROM ... JOIN form shown in #Avitus's answer is that it will no longer report if there are multiple matching rows - it will just silently pick one of them - which one is never made clear.
Now I look at the query again, I'm not sure it even needs a WHERE clause now. I think this is the same:
Update kre.CustomerOrderLineCopy
SET DepNo = (
SELECT customerordercopy.DepNo
FROM kre.CustomerOrderCopy
WHERE CustomerOrderLineCopy.OrderCopyNo = kre.CustomerOrderCopy.OrderCopyNo)

Need to use information from one qry to dictate an action on another

Ok so this is going to sound a little complicated. I want to somehow put some kind of function that will divide a table value by two when its Policy number matches up with a policy number in another table.
Here is the query where I want that functions
SELECT
qryReinsuranceDPA1_izzy.POLICY_NO,
qryReinsuranceDPA1_izzy.PHASE_CODE,
qryReinsuranceDPA1_izzy.SUB_PHASE_CODE,
qryReinsuranceDPA1_izzy.SchedNP,
qryReinsuranceDPA1_izzy.ProdType,
Sum(qryReinsuranceDPA1_izzy.SumOfAMOUNT_INFORCE) AS SumOfSumOfAMOUNT_INFORCE,
Sum(qryReinsuranceDPA1_izzy.SumOfPUA_FACE) AS SumOfSumOfPUA_FACE,
Sum(qryReinsuranceDPA1_izzy.SumOfOYT_FACE) AS SumOfSumOfOYT_FACE, TotalDPA = sum(case when qryReinsuranceDPA1_izzy.[SumOfNetDefExtraAdj] Is Null then qryReinsuranceDPA1_izzy.[SumOfNetDefPremiumAdj] else qryReinsuranceDPA1_izzy.[SumOfNetDefPremiumAdj] +qryReinsuranceDPA1_izzy.[SumOfNetDefExtraAdj] end),
qryReinsuranceDPA1_izzy.SumOfGROSS_ANNLZD_PREM,
qryReinsuranceDPA1_izzy.SumOfStatNetPremium,
qryReinsuranceDPA1_izzy.[SumOfStatNetPremium]/qryReinsuranceDPA1_izzy.[SumOfGROSS_ANNLZD_PREM] AS NetToGrossRatio,
qryReinsuranceDPA1_izzy.NetvsGrossInd,
DPA_NetPrem = case when qryReinsuranceDPA1_izzy.[NetvsGrossInd]='Net' then sum(qryReinsuranceDPA1_izzy.[SumOfStatNetPremium]) else sum([qryReinsuranceDPA1_izzy].[SumOfGROSS_ANNLZD_PREM]) end,
qryPolicyListforNYDefPRemAsset_Re.ReinType AS ReinType,
Sum(qryPolicyListforNYDefPRemAsset_Re.ReinsAmount) AS SumOfReinsAmount,
qryPolicyListforNYDefPRemAsset_Re.[ReinsAmount]/(qryReinsuranceDPA1_izzy.[SumOfAMOUNT_INFORCE]+qryReinsuranceDPA1_izzy.[SumOfOYT_FACE]+qryReinsuranceDPA1_izzy.[SumOfPUA_FACE]) AS [Reins%],
qryPolicyListforNYDefPRemAsset_Re.ReinsStatRsv AS ReinsStatRsv,
Sum(qryPolicyListforNYDefPRemAsset_Re.SumOfGROSS_ANNLZD_PREM) AS ReinsPrem, qryReinsuranceDPA1_izzy.PAID_TO_DATE,
qryReinsuranceDPA1_izzy.VAL_DATE,
qryReinsuranceDPA1_izzy.ISSUE_DATE
FROM qryPolicyListforNYDefPRemAsset_Re RIGHT JOIN
qryReinsuranceDPA1_izzy
ON
qryReinsuranceDPA1_izzy.POLICY_NO = qryPolicyListforNYDefPRemAsset_Re.POLICY_NO
AND qryReinsuranceDPA1_izzy.PHASE_CODE = qryPolicyListforNYDefPRemAsset_Re.PHASE_CODE AND
qryReinsuranceDPA1_izzy.SUB_PHASE_CODE= qryPolicyListforNYDefPRemAsset_Re.SUB_PHASE_CODE
GROUP BY
qryReinsuranceDPA1_izzy.POLICY_NO,
qryReinsuranceDPA1_izzy.PHASE_CODE,
qryReinsuranceDPA1_izzy.SUB_PHASE_CODE,
qryReinsuranceDPA1_izzy.SchedNP,
qryReinsuranceDPA1_izzy.ProdType,
qryReinsuranceDPA1_izzy.SumOfGROSS_ANNLZD_PREM,
qryReinsuranceDPA1_izzy.SumOfStatNetPremium,
qryReinsuranceDPA1_izzy.[SumOfStatNetPremium]/qryReinsuranceDPA1_izzy.[SumOfGROSS_ANNLZD_PREM],
qryReinsuranceDPA1_izzy.NetvsGrossInd,
qryPolicyListforNYDefPRemAsset_Re.ReinType,
qryPolicyListforNYDefPRemAsset_Re.[ReinsAmount]/(qryReinsuranceDPA1_izzy.[SumOfAMOUNT_INFORCE]+qryReinsuranceDPA1_izzy.[SumOfOYT_FACE]+qryReinsuranceDPA1_izzy.[SumOfPUA_FACE]),
qryPolicyListforNYDefPRemAsset_Re.ReinsStatRsv,
qryReinsuranceDPA1_izzy.PAID_TO_DATE,
qryReinsuranceDPA1_izzy.VAL_DATE,
qryReinsuranceDPA1_izzy.ISSUE_DATE
GO
and this is the qry that contains the policy numbers that I want divided by 2 in the above qry.
SELECT
qryReinsuranceDPA1.POLICY_NO,
qryReinsuranceDPA1.PHASE_CODE,
qryReinsuranceDPA1.SUB_PHASE_CODE,
qryReinsuranceDPA1.ProdType,
TotalDPA = Sum(case when [SumOfNetDefExtraAdj] Is Null then [SumOfNetDefPremiumAdj] else [SumOfNetDefPremiumAdj] + SumOfNetDefExtraAdj end),
Sum(1) AS Expr1
FROM qryPolicyListforNYDefPRemAsset_Re RIGHT JOIN qryReinsuranceDPA1
ON
qryReinsuranceDPA1.POLICY_NO = qryPolicyListforNYDefPRemAsset_Re.POLICY_NO AND
qryReinsuranceDPA1.PHASE_CODE= qryPolicyListforNYDefPRemAsset_Re.PHASE_CODE AND
qryReinsuranceDPA1.SUB_PHASE_CODE = qryPolicyListforNYDefPRemAsset_Re.SUB_PHASE_CODE
GROUP BY qryReinsuranceDPA1.POLICY_NO,
qryReinsuranceDPA1.PHASE_CODE,
qryReinsuranceDPA1.SUB_PHASE_CODE,
qryReinsuranceDPA1.ProdType
HAVING (((Sum(1))<>1))
GO
quick example. Say that the Policy number 064543200 is located in the results of that second qry. I then want the number located in first qry in Total DPA assosciated with that Policy number to be divided by 2.
If this is still confusing please let me know and I will try to explain better. Both are views.

SSAS -> KPI Creation -> How to create a kpi that compares the rank of a customer on one day compared to the previous day?

I have been working on creating a kpi that compares the rank of a customer on a specific date compared to the previous day. In turn you would be able to see if that customer has went up in rank or down in rank in terms of whatever the list was generated by. In my situation they are ordered by revenue.
I am able to rank my customers via the rank function easily enough and provide the report but when it comes to creating the kpi of comparing these ranks across days I am struggling in figuring out how this should be approached. The rank itself is not something stored as data it is something that I will need to create on the fly via the rank function.
Here is an example of my mdx query that I am using to create my initial starting report that provides me with rank of customers without a date splice:
WITH SET [RevRank] AS
ORDER (
[Customer].[Customer Id].CHILDREN ,
[Measures].[Revenue], BDESC)
MEMBER [Measures].[RANKRevenue] AS RANK([Customer].[Customer Id].CurrentMember, [RevRank] )
SELECT NON EMPTY { [Measures].[Revenue], [Measures].[Fact Order Count], [Measures].[RANKRevenue] } ON COLUMNS,
NON EMPTY TopCount( { ([RevRank] ) } , 100, [Measures].[Revenue]) ON ROWS
FROM [DW]
From this I am attempting to splice in a specific date (day) and then compare that rank to a previous day within a kpi. So, starting off I am working on breaking this query up. I created a pre calculated set and pre calculated member to help me do this more easily. Now I am just trying to figure out how to create this set and member by a day and then I can at least produce a comparison between one day and the next.
01/26/2012 Update: Ok, I am a bit further down the road on this, but I am still having issues with getting the rank to pull into my query, the query below has nulls for the rankings. Hopefully someone can see the issue with this query.
WITH MEMBER [Measures].[PrevDayRevenue] AS
( [Measures].[Revenue], ParallelPeriod ([Date Link].[PK Date].[PK Date],1))
SET [RevRankPrevOrder] AS
ORDER (
[Customer].[Customer Id].Members ,
[Measures].[PrevDayRevenue],
BDESC)
MEMBER [Measures].[RANKRevenuePrevOrder] AS RANK([Customer].CurrentMember, [RevRankPrevOrder])
SET [RevRankCurrOrder] AS
ORDER (
[Customer].[Customer Id].Members ,
[Measures].[Revenue],
BDESC)
MEMBER [Measures].[RANKRevenueCurrOrder] AS RANK([Customer].CurrentMember, [RevRankCurrOrder])
SELECT NON EMPTY { [Measures].[Revenue], [Measures].[PrevDayRevenue], [Measures].[RANKRevenuePrevOrder], [Measures].[RANKRevenueCurrOrder] } ON COLUMNS,
NON EMPTY { ( [RevRankCurrOrder] ) } ON ROWS
FROM [DW]
WHERE {[Date Link].[PK Date].&[2012-01-08T00:00:00]}
You can use the ParallelPeriod function to calculate the rank for the prior day. This will also need to be done on the fly.
Then you can just compare the two in your KPI value...
CASE
WHEN [Customer Rank Yesterday] - [Customer Rank Today] > 0 THEN 1
WHEN [Customer Rank Yesterday] - [Customer Rank Today] = 0 THEN 0
ELSE -1
END
Here is my finished query, hope this helps someone else. :
WITH MEMBER [Measures].[PrevDayRevenue] AS
( [Measures].[Revenue], ParallelPeriod ([Date Link].[PK Date].[PK Date],1))
SET [RevRankPrevOrder] AS
ORDER (
[Customer].[Customer Id].CHILDREN ,
[Measures].[PrevDayRevenue],
BDESC)
MEMBER [Measures].[RANKRevenuePrevOrder] AS
RANK(
[Customer].[Customer Id].CurrentMember,
[RevRankPrevOrder])
SET [RevRankCurrOrder] AS
ORDER (
[Customer].[Customer Id].CHILDREN,
[Measures].[Revenue],
BDESC)
MEMBER [Measures].[RANKRevenueCurrOrder] AS RANK([Customer].[Customer Id].CurrentMember, [RevRankCurrOrder])
SELECT NON EMPTY { [Measures].[Revenue], [Measures].[PrevDayRevenue], [Measures].[RANKRevenuePrevOrder], [Measures].[RANKRevenueCurrOrder] } ON COLUMNS,
NON EMPTY { ( [RevRankCurrOrder] ) } ON ROWS
FROM [DW]
WHERE {[Date Link].[PK Date].&[2012-01-10T00:00:00]}

Dynamic column value with group by (sql server and Linq)

i have a table Plan with following sample data
i want to aggregate the result by PlanMonth and for PlanStatus i want that if any of its (in a group) values is Drafted i get drafted in the result and Under Approval otherwise. i have done it using following query
select PlanMonth, case when Flag=1 then 'Drafted' else 'Under Approval' end as PlanStatus
from
(select p.PlanMonth, Max(CASE WHEN p.PlanStatus = 'Drafted' THEN 1 ELSE 0 END) Flag
from Plans p
group by p.PlanMonth
) inquery
i have consulted this blog post. Is there something wrong with it? Moreover, if someone can help me translate it to linq i will be grateful
The query you have will work.
With the sample data you have provided it can be simplified a bit.
select p.PlanMonth,
min(p.PlanStatus) as PlanStatus
from Plans as p
group by p.PlanMonth
This will not work if you have values in PlanStatus that is alphabetically sorted before Drafted.
Following Linq query worked for me
return (from p in db.mktDrVisitPlans
group p by p.PlanMonth into grop
select
new VMVisitPlan
{
PlanMonth = grop.Key
PlanStatus = grop.Any(x=>x.p.PlanStatus == "Drafted")?"Hold":"Under Approval",
}).ToList();

Resources