iif in dimension member (MDX) - mdx

I need create a "business rule" on a new metric that consider some values on "condition a" and others values on "condition b" and this condition is before or after a date.
Being more specific: if date is before 2010-11-01, the metric will sum values A + B; if not, the metric will sum values C + D.
My "Period" dimension has like a key the date but in this format 20101101 and I try the follow code:
iif(
[Period].[Period].[Date] < [Period].[Period].[Date].&[20101101],
(
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[1]&[69552],[Measures].[Saldo Final]) +
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[2]&[69463],[Measures].[Saldo Final]) +
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[3]&[53054],[Measures].[Saldo Final]) +
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[4]&[63740],[Measures].[Saldo Final]) +
( [Plano Contas].[Plano de Contas].[Conta Contábil].&[273],[Measures].[Saldo Final]) +
( [Plano Contas].[Conta Contábil].&[464],[Measures].[Saldo Final])
),
(
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[1]&[69552],[Measures].[Saldo Final]) +
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[2]&[69463],[Measures].[Saldo Final]) +
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[3]&[53054],[Measures].[Saldo Final]) +
( [Plano Contas].[Plano de Contas].[Totalizadora 4].&[4]&[63740],[Measures].[Saldo Final])
)
)
I believe that my mistake is in the beginning of the "iif" but I don't know how solve this situation.
The key of my Period dimension (20101101) is a numeric field, not a date field.

The IIF condition does not compare the values of the key of the two members but the cube values of the two single member tuples (using the current/default [Measures]).
Assuming we can compare directly the values of these keys (it looks like the numeric format yyyymmdd is fine for that) you could do the following using the properties function :
IIF ( [Period].[Period].currentMember.properties( "key", TYPED ) < 20101101 )
You can check that MDX gentle introduction for more details about MDX notations and concepts.

Related

SELECT DISTINCT FROM 3 columns with all the records

I would like to query and get for all the records with the same datetime ,filter by Type , Provider and Operator.
If I run select distinct EventStamp I get all the records that I need, but I miss the type , provider and operator.
Like the screenshots if I have the Type OPR I need this record
If all the types are DDE I need Provider RDSSERVER\Intouch.
SELECT [EventStamp] ,[TagName] ,[Description],[Area] ,[Type],[Value], Antes FROM
(
SELECT distinct [EventStamp]
,[TagName]
,[Description]
,[Area]
,[Type]
,[Value]
,[CheckValue] as Antes
FROM [dbo].[v_EventHistory] where type = 'OPR'
UNION
SELECT distinct [EventStamp]
,[TagName]
,[Description]
,[Area]
,[Type]
,[Value]
,[CheckValue] as Antes
FROM [dbo].[v_EventHistory] where type = 'DDE'
)as EV order by EventStamp desc
With this code I miss the type , provider and operator.
I nee like this
Shared query from Hannover (Thank you)
It sounds like you need to use IN to identify all the records with the same Event Stamp, Provider and Operator.
SELECT *
FROM [dbo].[v_EventHistory]
WHERE CAST([EventStamp] AS VARCHAR(25)) + [Provider] + [Operator]
IN ( SELECT DISTINCT CAST([EventStamp] AS VARCHAR(25)) + [Provider] + [Operator]
FROM [dbo].[v_EventHistory]
WHERE [type] IN ( 'OPR', 'DDE' )
)
ORDER BY EventStamp DESC

About currentmember in SSAS & MDX

I will show you my thoughts about an MDX request, these thoughts are wrong because I don't get the expected result, but why?
The select statement is as follow:
SELECT {nballPatsTransfusedOneSpe , nballPatsOneSpe,nballPatsTransfusedOfSameSpes ,nballPatsOfSameSpes ,localRate} ON 0
FROM [BDD PBM]
Only one variable is of interest: localRate.
It is defined as:
member localRate as ([Dim misc].[Speciality Id].&[{754EFA13-AA1B-4E57-AB73-893AF7C52127}], rate)
I think of localRate as a tuple containing 2 explicit informations : one for a Speciality Id, and the other as a measure(even it doesn't belong to [Measures]), the implicit dimensions of the cube being calculated following standard rules(Default member, All members, First member). Both produce a number, as rate produces an integer. And I think that until the end of the request, the defaultmember of the 'Speciality Id' attribute is the Guid shown above(the hexa number), anywhere it could appears in 'Dim misc'(in an attribute hierarchy, or in all the user hierarchies).
rate is defined as:
MEMBER rate AS (existing([Dim misc].[SpePats2].CurrentMember, allPatsOneSpe )).count
It filters the list of patients (allPatsOneSpe) by the speciality given in localRate, and then count the number of rows. Globally, it returns the number of patients in the given speciality. I can't set a request with the 'speciality Id' in rows and the rate in columns as I will have to compute percents with a set of speciality ids, so I must have a list of specialities and a member rate which, given a speciality id, returns a numerator divided by a denominator(only the denominator is given here).
allPatsOneSpe is as follow:
SET allPatsOneSpe AS Descendants([Dim misc].[SpePats].currentmember,2)
And this is surely where the error is located.
Do these ideas right?
thank you.
Here is the entire request:
with
MEMBER spename AS [DimTransfusion].[TransfusionPatients].[Speciality Id].&[{7XXXXXX7-AA1B-4E57-AB73-89XXXXXXXX27}].FirstChild.MemberValue
SET spesSame AS filter([Dim misc].[SpePats].[Speciality Id].MEMBERS
,[Dim misc].[SpePats].CurrentMember.FirstChild.MemberValue = spename)--filter
SET spesSameTransfusion AS filter([DimTransfusion].[TransfusionPatients].[Speciality Id].MEMBERS
,[DimTransfusion].[TransfusionPatients].CurrentMember.FirstChild.MemberValue = spename)--filter
SET allPatsOfSameSpes AS Generate(spesSame, Descendants([Dim misc].[SpePats].CurrentMember,2))
SET allPatsTransfusedOfSameSpes AS Generate(spesSameTransfusion , Descendants([DimTransfusion].[TransfusionPatients].CurrentMember,3))
MEMBER nballPatsOfSameSpes AS allPatsOfSameSpes.count
MEMBER nballPatsTransfusedOfSameSpes AS allPatsTransfusedOfSameSpes.count
SET allPatsOneSpe AS Descendants([Dim misc].[SpePats].CurrentMember,2)
SET allPatsTransfusedOneSpe AS Descendants([DimTransfusion].[TransfusionPatients].[Speciality Id].[{XXXXXXX7-AA1B-4E57-AB73-8XXXXXXXX}],2)
MEMBER nballPatsOneSpe AS allPatsOneSpe.count
MEMBER nballPatsTransfusedOneSpe AS allPatsTransfusedOneSpe.count
MEMBER rateOneSpe AS nballPatsTransfusedOneSpe / nballPatsOneSpe
MEMBER [Measures].rate AS --(existing([Dim misc].[SpePats2].CurrentMember, filter(allPatsTransfusedOneSpe ,true ) )).count
-- /
(existing([Dim misc].[SpePats2].CurrentMember, allPatsOneSpe )).count
SET OrderedData AS ORDER(
NONEMPTY(spesSame , [Measures].rate),[Measures].rate, BASC)
MEMBER [Measures].[RowCount] AS COUNT (OrderedData)
MEMBER [Measures].[i0p02] AS ( .02* ( [RowCount] - 1 ) ) + 1
MEMBER [Measures].[i0p02Lo] AS FIX([i0p02]) - 1
MEMBER [Measures].[i0p02Rem] AS ([i0p02] - FIX([i0p02]))
MEMBER [Measures].[n0p02Lo] AS (OrderedData.Item([i0p02Lo]), [Measures].[rate])
MEMBER [Measures].[n0p02Hi] AS (OrderedData.Item([i0p02Lo] + 1), [Measures].[rate])
MEMBER [Measures].[PCT0p02] AS [n0p02Lo] + ( [i0p02Rem] * ( [n0p02Hi] - [n0p02Lo] ))
MEMBER [Measures].[i0p2] AS ( .2* ( [RowCount] - 1 ) ) + 1
MEMBER [Measures].[i0p2Lo] AS FIX([i0p2]) - 1
MEMBER [Measures].[i0p2Rem] AS ([i0p2] - FIX([i0p2]))
MEMBER [Measures].[n0p2Lo] AS (OrderedData.Item([i0p2Lo]), [Measures].[rate])
MEMBER [Measures].[n0p2Hi] AS (OrderedData.Item([i0p2Lo] + 1), [Measures].[rate])
MEMBER [Measures].[PCT0p2] AS [n0p2Lo] + ( [i0p2Rem] * ( [n0p2Hi] - [n0p2Lo] ))
MEMBER [Measures].[i0p5] AS ( .5* ( [RowCount] - 1 ) ) + 1
MEMBER [Measures].[i0p5Lo] AS FIX([i0p5]) - 1
MEMBER [Measures].[i0p5Rem] AS ([i0p5] - FIX([i0p5]))
MEMBER [Measures].[n0p5Lo] AS (OrderedData.Item([i0p5Lo]), [Measures].[rate])
MEMBER [Measures].[n0p5Hi] AS (OrderedData.Item([i0p5Lo] + 1), [Measures].[rate])
MEMBER [Measures].[PCT0p5] AS [n0p5Lo] + ( [i0p5Rem] * ( [n0p5Hi] - [n0p5Lo] ))
--MEMBER [Measures].[PCT0p5] AS Median(OrderedData, [Measures].[Weight])
MEMBER [Measures].[i0p8] AS ( .8* ( [RowCount] - 1 ) ) + 1
MEMBER [Measures].[i0p8Lo] AS FIX([i0p8]) - 1
MEMBER [Measures].[i0p8Rem] AS ([i0p8] - FIX([i0p8]))
MEMBER [Measures].[n0p8Lo] AS (OrderedData.Item([i0p8Lo]), [Measures].[rate])
MEMBER [Measures].[n0p8Hi] AS (OrderedData.Item([i0p8Lo] + 1), [Measures].[rate])
MEMBER [Measures].[PCT0p8] AS [n0p8Lo] + ( [i0p8Rem] * ( [n0p8Hi] - [n0p8Lo] ))
MEMBER [Measures].[i0p98] AS ( .98* ( [RowCount] - 1 ) ) + 1
MEMBER [Measures].[i0p98Lo] AS FIX([i0p98]) - 1
MEMBER [Measures].[i0p98Rem] AS ([i0p98] - FIX([i0p98]))
MEMBER [Measures].[n0p98Lo] AS (OrderedData.Item([i0p98Lo]), [Measures].[rate])
MEMBER [Measures].[n0p98Hi] AS (OrderedData.Item([i0p98Lo] + 1), [Measures].[rate])
MEMBER [Measures].[PCT0p98] AS [n0p98Lo] + ( [i0p98Rem] * ( [n0p98Hi] - [n0p98Lo] ))
member Ecart1 as [Measures].[PCT0p2]-[Measures].[PCT0p02]
member Ecart2 as [Measures].[PCT0p5]-[Measures].[PCT0p2]
member Ecart3 as [Measures].[PCT0p8] - [Measures].[PCT0p5]
member Ecart4 as [Measures].[PCT0p98] -[Measures].[PCT0p8]
member localRate as ([Dim misc].[Speciality Id].&[{77-AA1B-4E57-AB73-27}], [Measures].rate)
SELECT{ PCT0p02, Ecart1, Ecart2, Ecart3, Ecart4 ,PCT0p98 ,localRate } on 0
--SELECT {nballPatsTransfusedOneSpe , nballPatsOneSpe,nballPatsTransfusedOfSameSpes ,nballPatsOfSameSpes ,localRate} ON 0
--SELECT {} ON 0, {OrderedData} ON 1
FROM [BDD PBM]
--[Dim misc].[SpePats].[Hospital Id].&[{274DED7-8605-EA4E741DF116}].&[CH de ABCD].&[{26FBAA2E661}]
--WHERE [Dim misc].[SpePats].&[{7-AA1B-4E57-AB73-89127}]

SQL -Place 2 decimal places in a runtime select -SQL

I have this select query :
SELECT Nombre, Tipo, Descripcion,Abierto,Cerrado, Latitud, Longitud,
SQRT( POW( 69.1 * ( Latitud - 19.55385 ) , 2 )
+ POW( 69.1 * ( - 99.21716 - Longitud )
* COS( Latitud / 57.3 ) , 2 ) ) AS distance
FROM Clientes
It works ok, but it sometimes returns a really long number (many decimal places) and I would like it to return the value with a decimal point with just two places.
I allready tried
CONVERT(DECIMAL(10,2),distance)
but I think my code is badly written.
It would be much appreciated if someone could give me an example or something!
Sorry for my english, I hope it's understandable. And thanks in advance!!
Use the function Round() to mathematical round and Cast to adjust the precision
Ex:
select Cast(ROUND(- 99.2171600000009669 ,2) as decimal(10,2))
Result
-99.22
In your query:
SELECT Nombre, Tipo, Descripcion,Abierto,Cerrado, Latitud, Longitud,
Cast(ROUND(SQRT( POW( 69.1 * ( Latitud - 19.55385 ) , 2 )
+ POW( 69.1 * ( - 99.21716 - Longitud )
* COS( Latitud / 57.3 ) , 2 ) ) ,2) as decimal(10,2)) AS distance
FROM Clientes
Order By Distance Desc

SSIS Combining multiple rows into a single row with multiple columns

I have a table that does not have a primary key, but has an ID field that could be used as a primary key. I would like to transform this table into something useable to track inserts, updates, and deletes. Just adding a Identity column is not a viable solution because the table gets recreated every evening.
The table looks something like:
ID Specialty
-- ---------
01 Fam Med
02 Fam Med
02 Int Med
03 Surgery
03 Thor Sur
03 Card Sur
04 Undersea
I would like to transform it into something like the following and use ID as the primary key:
ID Specialty1 Specialty2 Specialty3
-- ---------- ---------- ----------
01 Fam Med
02 Fam Med Int Med
03 Surgery Thor Sur Card Sur
04 Undersea
I was leaning toward using the SQL pivot operator, but I am not familiar enough with pivots and I am not sure it is appropriate in this case.
Thank you in advance for your input.
The SQL you would need to do the PIVOT is:
SELECT ID,
Specialty1,
Specialty2,
Specialty3
FROM ( SELECT ID,
Specialty,
SpecialtyNum = 'Specialty' +
CAST(ROW_NUMBER() OVER(PARTITION BY ID
ORDER BY Specialty) AS VARCHAR(10))
FROM T
) AS t
PIVOT
( MAX(Specialty)
FOR SpecialtyNum IN ([Specialty1], [Specialty2], [Specialty3])
) AS pvt;
Example on SQL Fiddle
The key is adding a further column that you can pivot on, so the result of the subquery:
SELECT ID,
Specialty,
SpecialtyNum = 'Specialty' +
CAST(ROW_NUMBER() OVER(PARTITION BY ID
ORDER BY Specialty) AS VARCHAR(10))
FROM T;
Gives you:
ID Specialty SpecialtyNum
-- --------- -------------
01 Fam Med Specialty1
02 Fam Med Specialty1
02 Int Med Specialty2
03 Surgery Specialty1
03 Thor Sur Specialty2
03 Card Sur Specialty3
04 Undersea Specialty1
Then you can pivot on the SpecialtyNum column. Since each value of specialtyNum is unique to an ID, there is no data loss through aggregation.
But with an unknown number of specialities you would need to generate this dynamically:
DECLARE #Cols NVARCHAR(MAX) =
STUFF(( SELECT DISTINCT ',[Specialty' + CAST(ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Specialty) AS VARCHAR(10)) + '] '
FROM T
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE #SQL NVARCHAR(MAX) =
'SELECT ID, ' + #Cols +
'FROM ( SELECT ID,
Specialty,
SpecialtyNum = ''Specialty'' +
CAST(ROW_NUMBER() OVER(PARTITION BY ID
ORDER BY Specialty) AS VARCHAR(10))
FROM T
) AS t
PIVOT
( MAX(Specialty)
FOR SpecialtyNum IN (' + #Cols + ')
) AS pvt;';
EXECUTE sp_executesql #SQL;
Example on SQL Fiddle

Count if or Count where in SQL

I have a data set of contracts and the nationalities of people working on them. A sample is as follows.
Contract Country
GTT001 DE
GTT001 DE
GTT001 US
BFF333 US
BFF333 US
BFF333 DE
HHH222 GB
HHH222 GB
HHH222 GB
I need a query that will count the number of people working on each contract from each country. So one that will produce a table like below:
DE US GB
GTT001 2 1 0
BFF333 1 2 0
HHH222 0 0 3
I am working in Access 2010. Is there a countif or some equivalent that will allow me to count values based on conditions?
You want to use GROUP BY using both contract and then country. This will give you a list like this:
Contract Country Count
GTT001 DE 2
GTT001 US 1
BFF333 US 2
BFF333 DE 1
HHH222 GB 3
Then you want to pivot those values to get it into the format you want. The 0s will still be missing...
DECLARE #Pivotcols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #Pivotcols = STUFF((SELECT distinct N',' + QUOTENAME([Country])
from [Contract]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select #Pivotcols
set #query = N'SELECT [Contract], ' + #Pivotcols + N'
from
(
SELECT [Contract]
,[Country]
FROM [TEST_DB].[dbo].[Contract]
) sourceTable
pivot
(
Count([Country])
for [Country] in (' + #Pivotcols + N')
) p '
execute sp_executesql #query;
The core query
SELECT * from
(SELECT [Contract]
,[Country]
FROM [TEST_DB].[dbo].[Contract]
) sT
pivot
(
Count([Country])
for [Country] in ([DE],[US],[GB])
) p
PIVOT will work, it's a bit more complicated but so raw sql you could GROUP BY, for example:
SELECT Contract, Country, COUNT(*)
FROM [YourTable]
GROUP BY Contract, Country
ORDER BY Country