I want to replicate this query in my Power BI:
SELECT n.codigonotario,
n.nombrenotario,
CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN COUNT(cp.indiceunico)END AS NUM_OPERACIONES,
CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN SUM(cp.bases)END AS NUM_BASES,
SUM(dc.valornumerico / (CASE ISNULL(p.MONEDA, 0)WHEN 0 THEN 166.386 ELSE 1 END)) AS TotalCuantias,
RTRIM(LTRIM(cp.indiceunico)) AS codigoconcepto,
cp.textoconcepto + ' (' + RTRIM(LTRIM(cp.indiceunico)) + ')' AS DESCRIPCIONCONCEPTO,
cdc.categoriacampo
FROM notarios n
INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))
INNER JOIN conceptosprotocolos cp ON cp.codigoprotocolo = p.codigoprotocolo
INNER JOIN datosconceptos dc ON dc.codigoprotocolo = p.codigoprotocolo
AND SUBSTRING(cp.path, 6, 4) = SUBSTRING(dc.path, 6, 4)
INNER JOIN camposdatosconceptos cdc ON cdc.codigocampodatos = dc.codigocampodatos
INNER JOIN conceptos c ON c.codigoconcepto = cp.codigoconcepto
WHERE p.fechaprotocolo >= '01/01/2022'
AND p.fechaprotocolo <= '31/12/2022'
AND n.codigonotario LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
AND (cdc.categoriacampo = 'CUANTIA'
OR cdc.categoriacampo = 'HONORARIOSBRUTO'
OR cdc.categoriacampo = 'HONORARIOSREDUCCION')
AND p.encargado LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
AND (p.codigoprotocolo LIKE 'p%'
OR p.codigoprotocolo LIKE 'c%')
AND cp.indiceunico LIKE CASE LEN(1)WHEN 0 THEN '%' ELSE 1 END
GROUP BY n.codigonotario,
n.nombrenotario,
cp.indiceunico,
cp.textoconcepto,
dc.path,
cdc.categoriacampo;
I already have the database and tables imported in my project:
And I know how to implement inner joins:
But some of those inner joins need substrings and other functions, starting with the first inner join:
INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))
You can't use SQL functions in Power BI, but you can use Power Query, so I'm struggling trying to replicate those here (it doesn't recognize 'MID' or 'LEFT').
let
Origen = Sql.Databases("LAPTOP-OSCAR"),
Far = Origen{[Name="Far"]}[Data],
dbo_NOTARIOS = Far{[Schema="dbo",Item="NOTARIOS"]}[Data],
#"Consultas combinadas" = Table.NestedJoin(dbo_NOTARIOS, {"CODIGONOTARIO"}, PROTOCOLOS, {"CODIGOPROTOCOLO"}, "PROTOCOLOS", JoinKind.Inner)
in
#"Consultas combinadas"
Could somebody help me to replicate the substring function in Power BI, please?
Related
I am trying to convert this query to a SQL Server view
SELECT
IIF([tblStockMovementsDate] ! [LocationType] = 3, [tblShops] ! [Type], [tblLocationType] ! [LocationTypeDesc]) AS [LocationTypeDesc],
tblStockMovementsDate.[Location],
qryAllLocations.[WarehouseName],
SUM (([tblStockMovementsdate] ! [MovementQtyHangers] + ([tblStockMovementsdate] ! [MovementQtyBoxes] * Iif(Isnull([qryGarmentsPerBox] ! [GarmentsPerBox]), 1, [qryGarmentsPerBox] ! [GarmentsPerBox]))) * [qryUnitPrice] ! [UnitPrice]) AS [TotalValue],
IIF ([tblShops] ! [Type] = 'Concession', 4, [tblStockMovementsDate] ! [LocationType]) AS [LocationType]
FROM
(((((tblStockMovementsDate
INNER JOIN
tblLocationType ON tblStockMovementsDate.[LocationType] = tblLocationType.[LocationType])
INNER JOIN
qryAllLocations ON tblStockMovementsDate.[Location] = qryAllLocations.[WarehouseRef])
LEFT JOIN
qryGarmentsPerBox ON (tblStockMovementsDate.[Location] = qryGarmentsPerBox.[WarehouseRef])
AND (tblStockMovementsDate.[StockCode] = qryGarmentsPerBox.[StockCode]))
LEFT JOIN
qryUnitPrice ON tblStockMovementsDate.[StockCode] = qryUnitPrice.[StockCode])
LEFT JOIN
tblShops ON tblStockMovementsDate.[Location] = tblShops.[ShopRef])
INNER JOIN
tblStock ON tblStockMovementsDate.[StockCode] = tblStock.[StockCode]
WHERE
((IIF ([tblShops].[Clearance] = 0, [tblStock].[DeadCode] = 0, [tblStock].[RemoveFromClearance] = 0) ) <> False)
GROUP BY
IIF ([tblStockMovementsDate] ! [LocationType] = 3, [tblShops] ! [Type], [tblLocationType] ! [LocationTypeDesc]),
tblStockMovementsDate.[Location],
qryAllLocations.[WarehouseName],
IIF ([tblShops] ! [Type] = 'Concession', 4, [tblStockMovementsDate] ! [LocationType])
ORDER BY
IIF ([tblShops] ! [Type] = 'Concession', 4, [tblStockMovementsDate] ! [LocationType])
but it won't produce an output, instead I keep getting this error:
Error in list of function arguments: '=' not recognized.
Error in list of function arguments: 'IS' not recognized.
Unable to parse query text.
Any help would be appreciated.
This is a shot in the dark. I did my best to decipher the code you posted originally.
I would recommend getting rid of those nested views. They are going to cause you serious anguish at some point. You will likely have to grab the queries from those views and move that to this query.
Notice how much cleaner this is when you use aliases instead of the Access default of slapping the table in front of every column. I also removed dozens of parenthesis groups that did nothing but make this hard to see. I also converted all your IIF expressions to case expressions since I don't know what version of sql you are using.
SELECT
case when smd.LocationType = 3
then tblShops.Type
else lt.LocationTypeDesc
end AS LocTypeDesc
, smd.Location
, al.WarehouseName
, Sum((smd.MovementQtyHangers + (smd.MovementQtyBoxes * Isnull(g.GarmentsPerBox, 1))) * qryUnitPrice.UnitPrice) AS TotalValue
, case when sh.Type = 'Concession'
then 4
else smd.LocationType
end AS LocType
FROM tblStockMovementsDate smd
INNER JOIN tblLocationType lt ON smd.LocationType = ll.LocationType
INNER JOIN qryAllLocations al ON smd.Location = al.WarehouseRef
LEFT JOIN qryGarmentsPerBox g ON smd.Location = g.WarehouseRef
AND smd.StockCode = g.StockCode
LEFT JOIN qryUnitPrice up ON smd.StockCode = up.StockCode
LEFT JOIN tblShops sh ON smd.Location = sh.ShopRef
INNER JOIN tblStock st ON smd.StockCode = st.StockCode
WHERE tblShops.Clearance <> 0
OR tblStock.DeadCode <> 0
OR tblStock.RemoveFromClearance <> 0
GROUP BY case when smd.LocationType = 3 then tblShops.Type else lt.LocationTypeDesc end
, smd.Location
, al.WarehouseName
, case when sh.Type = 'Concession' then 4 else smd.LocationType end
order by LocType
I am working on Microsoft SQL Server 2014 and I have the following SQL query which works:
SELECT
h.entidade, h.datadoc, h.tipodoc, h.numdoc,
(SELECT valortotal -
(SELECT COALESCE(SUM(l.valorrec), 0)
FROM LinhasLiq as l
INNER JOIN cabliq ON l.IdCabLiq = CabLiq.id
INNER JOIN Historico ON L.IdHistorico = Historico.id
WHERE cabliq.DataDoc < '01/05/2015'
AND historico.id = h.id)) as 'valor pendente',
coalesce(documentosCCT.Descricao,'')
+' '+ CASE WHEN h.modulo<>'V' THEN coalesce(documentosVenda.Descricao,'') else'' END
+' '+ coalesce(h.descricao,'') AS descricaogeral
FROM
Historico h
LEFT JOIN
documentosCCT ON h.TipoDoc = documentosCCT.Documento
LEFT JOIN
documentosVenda ON h.Tipodoc = documentosVenda.Documento
WHERE
h.entidade = 'ta0141' AND
(h.tipoentidade = 'C' OR h.tipoentidade = 'F')
ORDER BY
datadoc ASC
and this specific expression
(select valortotal - (SELECT COALESCE(SUM(l.valorrec),0) from LinhasLiq as l
inner join cabliq on l.IdCabLiq = CabLiq.id
inner join Historico on L.IdHistorico = Historico.id
where cabliq.DataDoc < '01/05/2015' and historico.id = h.id)) as 'valor pendente'
returns a lot of 0 values, so how can I put this entire expression in a having X > 0 clause, or any other way as long as the rows with this expression = 0 doesn't show?
Many thanks.
i don't know what is your circumstances if it is feasible try to make query in single select statement instead of multiple
Don't make an alias valor pendente like that should be valorpendente
Now you can use CTE
;WITH CTE AS
(
-- YOUR QUERY
)
SELECT * FROM CTE
WHERE valorpendente > 0
How do I create Stored Procedure on these queries and he output should show which check the anomaly was captured from, along with all the relevant data.
SELECT cm.Cust_id, cm.cust_ref_id4, cm.cust_ref_id3, cm.plan_group, cm.Company_name, cm.Cust_firstname, cm.Cust_lastname
COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID, c3.CompanyName FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID AND cm.cust_ref_id3 = c.pkCustomerID AND cm.cust_ref_id3 >= 1000000 AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN ('A','P','R','G') AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL ORDER BY cust_ref_id4;
and
SELECT [pkCustomerID],b.[pkContractID],[pkCustomerTypeID],[CustomerType],b.[ContractType] AS Contractype1,c.[ContractType]
AS Contractype2 FROM [CORE].[dbo].[Customers] a
JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (SELECT [pkContractID],[ContractType],[fkCustomerID] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE [ContractType] NOT LIKE 'Holdover%')b ON a.pkCustomerID=b.fkCustomerID
LEFT JOIN (SELECT [pkContractID],[fkCustomerID],[ContractType] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE ContractType LIKE 'Holdover%')c ON b.fkCustomerID=c.fkCustomerID WHERE [CustomerType] IN ('Customer','Former Customer') AND (b.ContractType IS NULL OR c.ContractType IS NULL)
You question is lacking a very important piece of information, the explanation of what you are trying to do. I took a shot in the dark here as a guess to what you might be looking for. BTW, I ran this through a formatter so it was legible.
SELECT 'Found in query1'
,cm.Cust_id
,cm.cust_ref_id4
,cm.cust_ref_id3
,cm.plan_group
,cm.Company_name
,cm.Cust_firstname
,cm.Cust_lastname
,COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID
,c3.CompanyName
FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID
AND cm.cust_ref_id3 = c.pkCustomerID
AND cm.cust_ref_id3 >= 1000000
AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN (
'A'
,'P'
,'R'
,'G'
)
AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL
SELECT 'Found in query 2'
,[pkCustomerID]
,b.[pkContractID]
,[pkCustomerTypeID]
,[CustomerType]
,b.[ContractType] AS Contractype1
,c.[ContractType] AS Contractype2
FROM [CORE].[dbo].[Customers] a
INNER JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (
SELECT [pkContractID]
,[ContractType]
,[fkCustomerID]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE [ContractType] NOT LIKE 'Holdover%'
) b ON a.pkCustomerID = b.fkCustomerID
LEFT JOIN (
SELECT [pkContractID]
,[fkCustomerID]
,[ContractType]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE ContractType LIKE 'Holdover%'
) c ON b.fkCustomerID = c.fkCustomerID
WHERE [CustomerType] IN (
'Customer'
,'Former Customer'
)
AND (
b.ContractType IS NULL
OR c.ContractType IS NULL
)
Here is my select statement. What I'm trying to do is if an account has more than one ID, I want the phone number to be NULL, ELSE I want the phone number to = phone_number_formatted:
SELECT
v_returned_inventory.order_id,
v_live_inventory.inet_event_description,
v_live_inventory.event_time,
v_cust_phone.phone_number_formatted,
v_live_inventory.event_date,
v_returned_inventory.section_name,
v_returned_inventory.add_usr,
v_live_inventory.num_seats,
v_returned_inventory.acct_id,
v_live_inventory.class_name,
AT_trans_for_emailTrigger.email_addr,
AT_trans_for_emailTrigger.cust_name_id,
premclub.name_first + ' ' + premclub.name_last AS name
FROM
v_returned_inventory
INNER JOIN
v_live_inventory
ON
LEFT(v_returned_inventory.event_name, 6) = LEFT(v_live_inventory.event_name, 6)
AND v_returned_inventory.orderNumber = v_live_inventory.other_info_1 INNER JOIN
AT_trans_for_emailTrigger
ON v_returned_inventory.order_id = AT_trans_for_emailTrigger.order_id
LEFT OUTER JOIN
v_cust_phone
on v_cust_phone.acct_id = v_returned_inventory.acct_id
LEFT OUTER JOIN
OPENQUERY(premclub, 'select name_first, name_last, cust_name_id from dba.v_cust_name') AS premclub
ON AT_trans_for_emailTrigger.cust_name_id = premclub.cust_name_id,
**CASE
WHEN (select
count(cust_name_id)
from
v_cust_phone) > 1 then null
else v_cust_phone.phone_number_formatted
END**
You have the CASE statement in the wrong place, it needs to be in the SELECT. Based on what you currently have, it appears that you might be able to do something like this:
SELECT v_returned_inventory.order_id,
v_live_inventory.inet_event_description,
v_live_inventory.event_time,
case when phone.cnt > 1 then null else v_cust_phone.phone_number_formatted end phone_number_formatted,
v_live_inventory.event_date,
v_returned_inventory.section_name,
v_returned_inventory.add_usr,
v_live_inventory.num_seats,
v_returned_inventory.acct_id,
v_live_inventory.class_name,
AT_trans_for_emailTrigger.email_addr,
AT_trans_for_emailTrigger.cust_name_id,
premclub.name_first + ' ' + premclub.name_last AS name
FROM v_returned_inventory
INNER JOIN v_live_inventory
ON LEFT(v_returned_inventory.event_name, 6) = LEFT(v_live_inventory.event_name, 6)
AND v_returned_inventory.orderNumber = v_live_inventory.other_info_1
INNER JOIN AT_trans_for_emailTrigger
ON v_returned_inventory.order_id = AT_trans_for_emailTrigger.order_id
LEFT OUTER JOIN v_cust_phone
on v_cust_phone.acct_id = v_returned_inventory.acct_id
LEFT OUTER JOIN
(
select count(cust_name_id) cnt, cust_name_id
from v_cust_phone
group by cust_name_id
) phone
on v_cust_phone.cust_name_id = phone.cust_name_id
LEFT OUTER JOIN OPENQUERY(premclub, 'select name_first, name_last, cust_name_id from dba.v_cust_name') AS premclub
ON AT_trans_for_emailTrigger.cust_name_id = premclub.cust_name_id
I am having problems with this case statement. I don't know what I am doing wrong but I get the error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
I have a case when the field equals a value then do a left outer join but if the field equals a different value then do a inner join.
This is my query:
SELECT
case
when oqt = '26' then
(Select qm.id_oqm, cast(isNull(id_eval, '') as varChar(50)) + ' - ' + qm.methodName as methodName, qm.methodName as actualMethod,cv.*
FROM OQMethods QM left outer join courseversions cv on cv.evalid = QM.id_eval and cv.courselanguage = 'EN' and cv.courseactive='Y' and cv.id_cp > 0
WHERE QM.id_oqt in (SELECT tempoq.oqt FROM tempoq INNER JOIN OQMethods ON tempoq.oqt = OQMethods.id_oqt)and active = 1)
END,
case
when oqt = '31' then
(Select qm.id_oqm, cast(isNull(id_eval, '') as varChar(50)) + ' - ' + qm.methodName as methodName, qm.methodName as actualMethod,cv.*
FROM OQMethods QM inner join courseversions cv on cv.evalid = QM.id_eval and cv.courselanguage = 'EN' and cv.courseactive='Y' and cv.id_cp > 0
where QM.id_oqt in (SELECT tempoq.oqt FROM tempoq INNER JOIN OQMethods ON tempoq.oqt = OQMethods.id_oqt) and active = 1)
END
from tempoq
The case is an expression that must evaluate to a value. The Select statements that you have return multiple values.
It would seem that you're trying to use Case like it's a C# switch? If that's the case, then you're likely better off with an IF ELSE IF construction.
It looks like you want to do something like this rather than using a CASE statement.
DECLARE #t int
-- This would contain your oqt value
SET #t =1
IF #t = 1
BEGIN
SELECT * FROM tableA
END
ELSE IF #t = 2
BEGIN
SELECT * FROM TableB
END
Select qm.id_oqm, cast(isNull(id_eval, '') as varChar(50)) + ' - ' + qm.methodName as methodName, qm.methodName as actualMethod,cv.*
FROM OQMethods QM
inner join tempoq on tempoq.oqt = QM.id_oqt
left outer join courseversions cv on cv.evalid = QM.id_eval and cv.courselanguage = 'EN' and cv.courseactive='Y' and cv.id_cp > 0
WHERE active = 1 and (tempoq.oqt = '26' or (tempoq.oqt = '31' and courseversions.* is not null))
left outer join means join OQMethods's data which even no match data from courseversions,
then filter the data with null courseversions.* that is inner join.
Hope I have the right understanding.