Uniquename function in mdx script - sql-server-2008-r2

I really need your help.
For a SSRS report, I have this mdx script:
select
{[Geographie].[Commune].[AHUY], [Geographie].[Commune].[BRETENIERE]} on columns
,{[Activite].[Branche].&[B], [Activite].[Branche].&[C]} on rows
from [ACSEL2]
where ([Measures].[CATTC], [Perimetre].[Perimetre].&[2], [Temps].[Annee].&[2006])
Please, I need to have the uniquename for the members that I have in columns
({[Geographie].[Commune].[AHUY], [Geographie].[Commune].[BRETENIERE]})
Please Can U help me to write this mdx script ?
Lidou

Declare a member using With statement, like this:
WITH MEMBER [Measures].[UniqueName] as [Geographie].[Commune].CurrentMember.UniqueName
Select
--Your select here
More details on CurrentMember

WITH
-- Geography metadata
MEMBER [Measures].[Geographie]
AS StrToValue ( #SelectionGeographie + ".Hierarchy.Currentmember.Uniquename" )
MEMBER [Measures].[Geographie_Label]
AS StrToValue( #SelectionGeographie + ".Hierarchy.CurrentMember.Member_Caption" )
SELECT NON EMPTY {
[Measures].[Geographie],
[Measures].[Geographie_Label],
[Measures].[11 VA]
} ON COLUMNS,
( STRTOSET ( "{" + #SelectionGeographie + "}") ,
STRTOSET ("{" + #SelectionActivite + "}" ))
ON ROWS
FROM [MyCube]
WHERE STRTOTUPLE ( "(" +#Annee + "," + #Perimetre + ")" )

Related

JPQL: How to rewrite postgres native query to JPQL query that uses filter keyword

Im trying to avoid using native query. I have this query that uses the filter function, how could I rewrite this to not use that and work in regular jpql?
#Query(
"SELECT time_bucket(make_interval(:intervalType), d.time) as groupedDate, " +
"CAST(d.team_Id as varchar) as teamId, CAST(d.service_Id as varchar) as serviceId, CAST(d.work_id as varchar) as workId, " +
"ROUND(CAST(count(d.value) filter ( where d.type = 'A') AS numeric) /" +
" (CAST(count(d.value) filter ( where d.type = 'B') AS numeric)), 4) as total " +
"FROM datapoint d " +
"WHERE d.team_Id = :teamId and d.service_id in :serviceIds and d.work_id = :workspaceId and d.type in ('A', 'B') " +
"AND d.time > :startDate " +
"GROUP BY groupedDate, d.team_Id, d.service_Id, d.workspace_Id " +
"ORDER BY groupedDate DESC",
nativeQuery = true
)
in the FROM statement you have to use the DAO object instead of the table name

aggregate function as tuple argument postgres

I want to pass aggregate function like min, max etc as query parameter using Tuple.
Below is my query:
"select $5(CAST (vol AS FLOAT)) AS agg_v, "
+ "time_bucket_gapfill" + "(($1::text || ' minutes')::interval, t) AS time_function_minute, "
+ "tag_id from rtdata "
+ "where tag_id = any($2) and t > $3 and t < $4 "
+ "GROUP BY (tag_id, time_function_minute) ORDER BY time_function_minute"
But I'm getting following exception:
io.vertx.pgclient.PgException: syntax error at or near
"("
at io.vertx.pgclient.impl.codec.ErrorResponse.toException(ErrorResponse.java:29)
at io.vertx.pgclient.impl.codec.PrepareStatementCommandCodec.handleErrorResponse(PrepareStatementCommandCodec.java:62)
at io.vertx.pgclient.impl.codec.PgDecoder.decodeError(PgDecoder.java:233)
at io.vertx.pgclient.impl.codec.PgDecoder.decodeMessage(PgDecoder.java:122)
at io.vertx.pgclient.impl.codec.PgDecoder.channelRead(PgDecoder.java:102)
at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:700)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:635)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:552)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:514)
at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1044)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:745)
But If I replace $5 with hardcode aggregate function it works. How can I pass aggregate function dynamically in this scenario?
RxJava code Snippet:
return txBegin()
.flatMapObservable(tx ->
tx.rxPrepare(abovesql)
.flatMapObservable(pq -> {
return pq.createStream(50,
Tuple.of(
evalBucketInterval(req),
req.getTags().toArray(new Integer[0]),
parse(req.getStartDate()),
parse(req.getEndDate()),
parse(req.getAggFunc())))
.toObservable();
})
.doAfterTerminate(tx::commit))
.map(this::toFuncJson);
PostgreSQL allows to use parameters only as values and doesn't understand when you try to use parameters for function names, table names, etc. So you cannot pass aggregate name as a parameter.
I suggest to work around it in your application by concatenating the string value containing the aggregate function name. I guess it can be something like, but I am not sure about the exact syntax and what limitations of your environment are:
"select "+ my_agg_func_name +"(CAST (vol AS FLOAT)) AS agg_v, "
+ "time_bucket_gapfill" + "(($1::text || ' minutes')::interval, t) AS time_function_minute, "
+ "tag_id from rtdata "
+ "where tag_id = any($2) and t > $3 and t < $4 "
+ "GROUP BY (tag_id, time_function_minute) ORDER BY time_function_minute"

UPDATE table via join in SQL

I am trying to normalize my tables to make the db more efficient.
To do this I have removed several columns from a table that I was updating several columns on.
Here is the original query when all the columns were in the table:
UPDATE myActDataBaselDataTable
set [Correct Arrears 2]=(case when [Maturity Date]='' then 0 else datediff(d,convert(datetime,#DataDate, 102),convert(datetime,[Maturity Date],102)) end)
from myActDataBaselDataTable
Now I have removed [Maturity Date] from the table myActDataBaselDataTable and it's necessary to retrieve that column from the base reference table ACTData, where it is called Mat.
In my table myActDataBaselDataTable the Account number field is a concatenation of 3 fields in ACTData, thus
myActDataBaselDataTable.[Account No]=ac.[Unit] + ' ' + ac.[ACNo] + ' ' + ac.[Suffix]
(where ac is the alias for ACTData)
So, having looked at the answers given elsewhere on SO (such as 1604091: update-a-table-using-join-in-sql-server), I tried to modify this particular update statement as below, but I cannot get it right:
UPDATE myActDataBaselDataTable
set dt.[Correct Arrears 2]=(
case when ac.[Mat]=''
then 0
else datediff(d,convert(datetime,'2014-04-30', 102),convert(datetime,ac.[Mat],102))
end)
from ACTData ac
inner join myActDataBaselDataTable dt
ON dt.[Account No]=ac.[Unit] + ' ' + ac.[ACNo] + ' ' + ac.[Suffix]
I either get an Incorrect syntax near 'From' error, or The multi-part identifier "dt.Correct Arrears 2" could not be bound.
I'd be grateful for any guidance on how to get this right, or suugestiopns about how to do it better.
thanks
EDIT:
BTW, when I run the below as a SELECT it returns data with no errors:
select case when [ac].[Mat]=''
then 0
else datediff(d,convert(datetime,'2014-04-30', 102),convert(datetime,[ac].[Mat],102))
end
from ACTData ac
inner join myActDataBaselDataTable dt
ON dt.[Account No]=ac.[Unit] + ' ' + ac.[ACNo] + ' ' + ac.[Suffix]
In a join update, update the alias
update dt
What is confusing is that in later versions of SQL you don't need to use the alias in the update line

Sum like operation for strings in t-sql

I already have query to concatenate
DECLARE #ids VARCHAR(8000)
SELECT #ids = COALESCE(#ids + ', ', '') + concatenatedid
FROM #HH
but if I have to do it inline how can I do that? Any help please.
SELECT sum(quantity), COALESCE(#ids + ', ', '') + concatenatedid from #HH
Thanks.
Use the XML PATH trick. You may need a CAST
SELECT
SUBSTRING(
(
SELECT
',' + concatenatedid
FROM
#HH
FOR XML PATH ('')
)
, 2, 7999)
Also:
Join characters using SET BASED APPROACH (Sql Server 2005)
Subquery returned more than 1 value

How do you concatenate strings inside of a CONTAINS in SQL Server 2008?

SQL Server 2008 is telling me that it doesn't like the "+" in the CONTAINS.
Not sure what I'm doing wrong here.
INSERT INTO dbo.tblImportTitles
(
ImportTitleGUID,
UserGUID,
TitleName,
TitleGUID
)
SELECT
ImportTitleGUID = T.Item.value('#ImportTitleGUID', 'uniqueidentifier'),
UserGUID = T.Item.value('#UserGUID', 'uniqueidentifier'),
TitleName = T.Item.value('#TitleName', 'varchar(255)'),
TitleGUID =
CASE
WHEN (SELECT TOP(2) COUNT(TitleGUID) FROM dbo.tblTitles WHERE CONTAINS(Title, '''' + T.Item.value('#TitleName', 'varchar(255)') + '''')) = 1
THEN (SELECT TitleGUID FROM dbo.tblTitles WHERE CONTAINS(Title,'''' + T.Item.value('#TitleName', 'varchar(255)') + ''''))
ELSE NULL
END
FROM #ImportTitlesInsertXml.nodes('BatchTitles/BTitle') AS T(Item)
Update
I'v decided to move this to a scalar function.
It was a lot easier to handle the code that way.
use QUOTENAME(#VARIABLE,'''') the + is not your problem.