What are other ways to get this result set - sql-server

What are other ways to get the same result set
I am using 4 tables
SELECT * FROM Terminal
SELECT * FROM Customer
SELECT * FROM Contract
SELECT * FROM ExternalTable
Data in these 4 tables are as below:
The query that i've written is
select ex.TerminalName,ex.CustomerName from ExternalTable ex
except
select t.TerminalName,ct.CustomerName from [Contract] c
inner join Terminal t on t.TerminalID=c.TerminalID
inner join Customer ct on ct.CustomerId=c.CustomerId
Which gets the below result
So just curious to know what are the other ways to get this same result

I'm not really what you are looking for, but here is another way to write the query that should produce the same results:
SELECT
ex.TerminalName,
ex.CustomerName
FROM
ExternalTable ex
WHERE
NOT EXISTS( SELECT
NULL
FROM
[Contract] c
INNER JOIN
Terminal t on t.TerminalID = c.TerminalID
INNER JOIN
Customer ct on ct.CustomerId = c.CustomerId
WHERE
t.TerminalName = ex.TerminalName
AND
ex.CustomerName = ct.CustomerName
)

This ought to be equivalent:
select ex.TerminalName,ex.CustomerName
from
ExternalTable ex
left outer join
(
[Contract] c
inner join Terminal t
on t.TerminalID=c.TerminalID
inner join Customer ct
on ct.CustomerId=c.CustomerId
)
on ex.TerminalName = t.TerminalName and ex.CustomerName = ct.CustomerName
where t.TerminalName is null and ct.CustomerName is null
You should note that except returns distinct results and to be strictly equivalent I would need to specify select distinct.

Here is a self-contained example that shows two alternatives.
One uses NOT IN, and the other uses a LEFT OUTER JOIN, but they should be equivalent.
--set up temp tables with dummy data to replicate the issue
declare #Terminal table(terminalid int,terminalname nvarchar(100));
insert into #Terminal select 1,'Terminal1' union select 2,'Terminal2'
declare #Customer table(customerid int,customername nvarchar(100));
insert into #Customer select 1,'Customer1' union select 2,'Customer2';
declare #Contract table(contractid int,terminalid int,customerid int,contractname nvarchar(100));
insert into #Contract select 1,1,1,'Contract1';
declare #ExternalTable table(externalid int,terminalname nvarchar(100),customername nvarchar(100),contractname nvarchar(100));
insert into #ExternalTable select 1,'Terminal1','Customer1','Contract1' union select 2,'Terminal2','Customer1','Contract1'
--SELECT * FROM #Terminal
--SELECT * FROM #Customer
--SELECT * FROM #Contract
--SELECT * FROM #ExternalTable
--goal: show records that are in the external table, but are not fully linked in the other tables
--original
select ex.TerminalName,ex.CustomerName from #ExternalTable ex
except
select t.TerminalName,ct.CustomerName from #Contract c
inner join #Terminal t on t.TerminalID=c.TerminalID
inner join #Customer ct on ct.CustomerId=c.CustomerId
--revised (left outer join method)
select et.TerminalName,et.CustomerName
from
#ExternalTable et
left join (
select ex.externalid
from
#Contract c
inner join #Terminal t on t.TerminalID=c.TerminalID
inner join #Customer ct on ct.CustomerId=c.CustomerId
inner join #ExternalTable ex on ex.terminalname = t.terminalname and ex.customername = ct.customername
) excludes on excludes.externalid = et.externalid
where excludes.externalid is null
--revised ("not in" method)
select et.TerminalName,et.CustomerName
from
#ExternalTable et
where et.externalid not in(
select ex.externalid
from
#Contract c
inner join #Terminal t on t.TerminalID=c.TerminalID
inner join #Customer ct on ct.CustomerId=c.CustomerId
inner join #ExternalTable ex on ex.terminalname = t.terminalname and ex.customername = ct.customername
)

Related

Is it possible to inner join a different table based on a sproc parameter?

I'm in charge of a legacy project and I was looking at simplifying or streamlining a bit.
What I want to do is something like:
declare #n int = 1
select * from table_a a
case when #n = 1 then inner join table_b b on b.x = a.x
else inner join table_c c a.x = c.x
end
The main reason I'm hoping this is possible is because I'm trying to get rid of a lot of repetition in the current sproc. Every time something changes, we have to make sure that each section is updated appropriately.
Currently it looks something like:
if #a = 1 begin
select (long list of columns but not all) from table_A
inner join table_2 a on table_A.a = table_2.a
left join table_B on table_A.c = table_B.c
where (several conditions here)
end
else if #= 2 begin
select (same long list of columns) from table_A
inner join table_3 a on table_A.a = table_3.a
left join table_B on table_A.c = table_B.c
where (same several conditions)
end
else
select (same list again) from table_A
inner join table_4 a on table_A.a = table_4.a
left join table_B on table_A.c = table_B.c
where (same conditions again)
end
In the example, tables 2, 3, and 4 are essentially identical as far as columns are concerned but are used to separate groups.
If it's not possible, I'm thinking I could combine all three of those tables into a single table and add a new column denoting the group and then inner join on that column along with the other one. I just figured that I'd rather not move data around if I didn't have to.
A variation of the following technique can be used, I'm using an outer join with null check.
declare #myVar int
set #myVar = 1
select
t1.id,
t1.nm,
coalesce(t2.nm, t3.nm) valu
from
table1 t1
left outer join
table2 t2 on (t1.id = t2.id and #myVar = 1)
left outer join
table3 t3 on (t1.id = t3.id and #myVar = 2)
where coalesce(t2.nm, t3.nm) is not null
The basic made-up schema in use:
select *
into table1
from
(select 1 id, 'a' nm union
select 2, 'b' union
select 3, 'c' union
select 7, 'j') a
select *
into table2
from
(select 1 id, 'a1' nm union
select 2, 'b1' union
select 3, 'c1' union
select 4, 'd1' ) a
select *
into table3
from
(select 1 id, 'a2' nm union
select 2, 'b2' union
select 3, 'c2' union
select 4, 'd2' union
select 5, 'e2' ) a
Does this work for you?
You can use an CROSS APPLY(...UNION ALL...) to effectively implement a conditional join to your middle table.
select (long list of columns but not all)
from table_A
cross apply (
select t2.c from table_2 t2 where t2.a = table_A.a and #a = 1
union all
select t3.c from table_3 t3 where t3.a = table_A.a and #a = 2
union all
select t4.c from table_4 t4 where t4.a = table_A.a and #a not in (1,2)
) X
left join table_B on X.c = table_B.c
where (several conditions here)
This should even run quite efficiently, assuming that you have indexes on table_2.a, table_3.a, table_4.a, and table_B.c.

SQL Server 2005 Select Data From Table1 and Table2 but if Table2 column1 value is null Select Data From Table3

My Query IS
SELECT TblPharmacyBillingDetails.UPBNo, TblMasterBillingData.IPDNo, InPatRegistration.PatTitle+PatientName, TblPharmacyBillingDetails.InvoiceNo, TblPharmacyBillingDetails.InvoiceDateTime, TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
but if TblMasterBillingData.IPDNo value is NULL select Data From TblMasterBillingData.OPDNo and
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.IPDNo
Method #1: Using UNION
SELECT * FROm
(
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.IPDNo,
InPatRegistration.PatTitle+PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
WHERE TblMasterBillingData.IPDNo IS NOT NULL
UNION ALL
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.OPDNo,
OutPatRegistration .PatTitle + PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.OPDNo
WHERE TblMasterBillingData.OPDNo IS NOT NULL
)Tmp
ORDER BY TblPharmacyBillingDetails.UPBNo
Method #2 Using ISNULL and LEFT JOIN
SELECT TblPharmacyBillingDetails.UPBNo,
ISNULL(TblMasterBillingData.IPDNo,TblMasterBillingData.OPDNo),
ISNULL(IP.PatTitle + IP.PatientName, OP.PatTitle + OP.PatientName),
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
LEFT JOIN InPatRegistration IP ON TblMasterBillingData.IPDNo = IP.IPDNo
LEFT JOIN outPatRegistration OP ON TblMasterBillingData.OPDNo = OP.OPDNo
ORDER BY TblPharmacyBillingDetails.UPBNo
You can write either case statement or ISNULL() function as shown below in the demo query.
SELECT
Orders.OrderID,
Case when Customers1.CustomerName is null then Customers2.CustomerName else Customers1.CustomerName
end as CustomerName, --way 1
ISNULL(Customers1.CustomerName, Customers2.CustomerName) as Customer, --way 2
Orders.OrderDate
FROM Orders
INNER JOIN Customers1 ON Orders.CustomerID = Customers1.CustomerID
INNER JOIN Customers2 ON Orders.CustomerID = Customers2.CustomerID
-- where your condition here
-- order by your column name
You can also check whether data is available or not in the table and join the table accordingly using if exists as shown below.
if exists(select 1 from tablename where columnname = <your values>)

SQL Server: Join tables in a loop going through table rows

I have a table with the following fiels: PicklistTable, PicklistColumnName, FormTable and FormColumnName. FormColumnName is a foreign key into PicklistTable that I need to join on PicklistColumnName. Basically I need to find out how many times each picklist values has been used on all forms that reference that picklist. So the query would look something like this (maybe??):
SELECT PicklistColumnName, count(FormColumnName1) + count(FormColumnName2) as Count
FROM PicklistTable
INNER JOIN FormTable1 ON PicklistColumnName = FormColumnName1
INNER JOIN FormTable2 ON PicklistColumnName = FormColumnName2
GROUP BY PicklistColumnName
Here is an example table:
PicklistTable PicklistColumnName FormTable FormColumnName
tblEthnicityValues Ethnicity_ID tblContact Contact_Ethnicity_ID
tblEthnicityValues Ethnicity_ID udfOHFTCYPLACIHAC FatherEthnicityID
tblEthnicityValues Ethnicity_ID udfOHFTCYPLACIHAC MotherEthnicityID
tblEthnicityValues Ethnicity_ID udfOHFTCYPLACIHAYP EthnicityID
tblEthnicityValues Ethnicity_ID udfOHFTCYPLACIHAYP FatherEthnicityID
tblEthnicityValues Ethnicity_ID udfOHFTCYPLACIHAYP MotherEthnicityID
tblEthnicityValues Ethnicity_ID udfOHFTCYPLACRHAC FatherEthnicityID
tblEthnicityValues Ethnicity_ID udfOHFTCYPLACRHAC MotherEthnicityID
So I would in this case need to join tblContact, udfOHFTCYPLACIHAC etc on Contact_Ethnicity_ID, FatherEthnicityID etc.
Can someone please help? I hope I explained it well enough.
Thanks!
Tanya
Assuming that the PicklistColumnName from PicklistTable table need not be present in both FormTable1 and FormTable2 tables, this query might solve your problem.
SELECT pt.PicklistColumnName, count(ft1.FormColumnName1) + count(ft2.FormColumnName2) as Count
FROM PicklistTable pt
LEFT OUTER JOIN FormTable1 ft1
ON pt.PicklistColumnName = ft1.FormColumnName1
LEFT OUTER JOIN FormTable2 ft2
ON pt.PicklistColumnName = ft2.FormColumnName2
GROUP BY pt.PicklistColumnName
Do you want to get the following SQL:
DECLARE #tb TABLE(PicklistTable VARCHAR(30),PicklistColumnName VARCHAR(30),FormTable VARCHAR(30),FormColumnName VARCHAR(30) )
INSERT INTO #tb(PicklistTable,PicklistColumnName,FormTable,FormColumnName)
SELECT 'tblEthnicityValues','Ethnicity_ID','tblContact','Contact_Ethnicity_ID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAC','FatherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAC','MotherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAYP','EthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAYP','FatherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAYP','MotherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACRHAC','FatherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACRHAC','MotherEthnicityID'
DECLARE #sql VARCHAR(max)
SELECT #sql='SELECT '+t.PicklistColumnName+',(0'+t.subCountSQL+') AS'+CHAR(13)+'Count FROM '+t.PicklistTable+CHAR(13)+t.subSQL FROM (
SELECT DISTINCT PicklistTable,PicklistColumnName,t2.* ,t3.*
FROM #tb AS t1
CROSS APPLY(SELECT 'INNER JOIN '+FormTable+' ON PicklistColumnName='+tt.FormTable+'.'+tt.FormColumnName+' '
FROM #tb AS tt WHERE tt.PicklistTable=t1.PicklistTable AND tt.PicklistColumnName=t1.PicklistColumnName
FOR XML PATH('')
) AS t2(subSQL)
CROSS APPLY(SELECT '+COUNT('+tt.FormTable+'.'+tt.FormColumnName +')'
FROM #tb AS tt WHERE tt.PicklistTable=t1.PicklistTable AND tt.PicklistColumnName=t1.PicklistColumnName
FOR XML PATH('')
) AS t3(subCountSQL)
)AS t
PRINT #sql
EXEC(#SQL)
The variable #SQL will be :
SELECT Ethnicity_ID,(0+COUNT(tblContact.Contact_Ethnicity_ID)+COUNT(udfOHFTCYPLACIHAC.FatherEthnicityID)+COUNT(udfOHFTCYPLACIHAC.MotherEthnicityID)+COUNT(udfOHFTCYPLACIHAYP.EthnicityID)+COUNT(udfOHFTCYPLACIHAYP.FatherEthnicityID)+COUNT(udfOHFTCYPLACIHAYP.MotherEthnicityID)+COUNT(udfOHFTCYPLACRHAC.FatherEthnicityID)+COUNT(udfOHFTCYPLACRHAC.MotherEthnicityID)) AS Count FROM tblEthnicityValues
INNER JOIN tblContact ON PicklistColumnName=tblContact.Contact_Ethnicity_ID INNER JOIN udfOHFTCYPLACIHAC ON PicklistColumnName=udfOHFTCYPLACIHAC.FatherEthnicityID INNER JOIN udfOHFTCYPLACIHAC ON PicklistColumnName=udfOHFTCYPLACIHAC.MotherEthnicityID INNER JOIN udfOHFTCYPLACIHAYP ON PicklistColumnName=udfOHFTCYPLACIHAYP.EthnicityID INNER JOIN udfOHFTCYPLACIHAYP ON PicklistColumnName=udfOHFTCYPLACIHAYP.FatherEthnicityID INNER JOIN udfOHFTCYPLACIHAYP ON PicklistColumnName=udfOHFTCYPLACIHAYP.MotherEthnicityID INNER JOIN udfOHFTCYPLACRHAC ON PicklistColumnName=udfOHFTCYPLACRHAC.FatherEthnicityID INNER JOIN udfOHFTCYPLACRHAC ON PicklistColumnName=udfOHFTCYPLACRHAC.MotherEthnicityID

Linked Servers and local tables join

I'm having a problem joining local tables and linked server tables. I can do it just by using inner joins, but it's taking me too long to execute the query.
I know there's a way to do it with OPENQUERY, but I can't get it.
Here's what I was doing in the beginning:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN [server].[db].[dbo].[TB_TEST] as ts
on local.L_ID = ts.L_ID
LEFT JOIN [server].[db].[dbo].[TB_EXE] as ex
on ts.A_ID = ex.T_ID
Now I'm trying to do this:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN (
SELECT *
FROM OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST'
) ts
on local.L_ID = ts.L_ID
left join OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE') ex
on ts.A_ID = ex.T_ID
Can you help me doing this the right way so the query runs quicker?
This kind of query's (with Linked Servers) may be slow because of bad connection of current instance to another or if on one of the servers is used older version of SQL Server. More info in this article.
I recommend you to use temp tables:
SELECT *
INTO #ts
FROM OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST;')
SELECT *
INTO #ex
FROM OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE;')
SELECT DISTINCT
l.L_ID
FROM dbo.local_table AS l
INNER JOIN #ts
on l.L_ID = ts.L_ID
LEFT JOIN #ex
on ts.A_ID = ex.T_ID
DROP TABLE #ts
DROP TABLE #ex
About your query's.
You use almost right syntax. Try it like:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN (
SELECT *
FROM OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST;')
) ts
on local.L_ID = ts.L_ID
left join (
SELECT *
FROM OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE;')
) ex
on ts.A_ID = ex.T_ID
Or:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST;') ts
on local.L_ID = ts.L_ID
left join OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE;') ex
on ts.A_ID = ex.T_ID
Also note that you are using LEFT JOIN with third table and don't use it at all.

Get the most value from another column

I want to get data historical and the production. My stored procedure is as follows:
ALTER PROCEDURE [dbo].[pCaRptACInactivas](
#CodAsesor VARCHAR(15),
#CodOficina VARCHAR(4))
AS
SET NOCOUNT ON
DECLARE #CodArbolConta VARCHAR(25)
IF #CodOficina = '%'
SET #CodArbolConta = '%'
ELSE
SELECT #CodArbolConta = CodArbolConta + '%' FROM tClOficinas WHERE CodOficina LIKE #CodOficina
SELECT
tabACInactivas.CodOficina,
tabACInactivas.NomOficina,
tabACInactivas.NomAsesor,
MAX(tabACInactivas.CodPrestamo) CodPrestamo,
tabACInactivas.CodAsociacion,
tabACInactivas.NombreAsociacion,
MAX(tabACInactivas.Ciclo) AS Ciclo,
COUNT(DISTINCT tabACInactivas.CodUsuario) AS CantSocias,
MAX(tabACInactivas.FechaEstado) AS FechaCancelacion--,
FROM ( SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaPrestamos.Ciclo, tCaPrCliente.CodUsuario, tCaPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaPrestamos.CodAsociacion INNER JOIN tCaPrCliente WITH(NOLOCK) ON tCaPrCliente.CodPrestamo = tCaPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaPrestamos Pr
INNER JOIN tCaPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaPrestamos.CodAsesor LIKE #CodAsesor AND tCaPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
UNION ALL
SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaHPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaHPrestamos.Ciclo, tCaHPrCliente.CodUsuario, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaHPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaHPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaHPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaHPrestamos.CodAsociacion INNER JOIN tCaHPrCliente WITH(NOLOCK) ON tCaHPrCliente.CodPrestamo = tCaHPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaHPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaHPrestamos Pr
INNER JOIN tCaHPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaHPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaHPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaHPrestamos.CodAsesor LIKE #CodAsesor AND tCaHPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
)tabACInactivas
GROUP BY tabACInactivas.CodAsociacion, tabACInactivas.NombreAsociacion, tabACInactivas.NomOficina, tabACInactivas.CodOficina, tabACInactivas.NomAsesor
I want the CantSocias column takes the most value of the Ciclo column, but not working
That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand. So I will go off of your last sentence:
I want the CantSocias column takes the most value of the Ciclo column,
but not working
Basically if you want to set a specific column to that, you can do something like this:
update YourTable
set CantSocias =
(
select max(Ciclo)
from YourOtherTable
)
-- here is where you can put a conditional WHERE clause
You may need to create a sub query to get the most value of Ciclo and join back to your query.
An example of what I mean is here:
create table #Product
(
ID int,
ProductName varchar(20)
)
insert into #Product(ID, ProductName)
select 1,'ProductOne'
union
select 2,'ProductTwo'
create table #ProductSale
(
ProductID int,
Number int,
SalesRegion varchar(20)
)
insert into #ProductSale(ProductID,Number,SalesRegion)
select 1,1500,'North'
union
select 1, 1200, 'South'
union
select 2,2500,'North'
union
select 2, 3200, 'South'
--select product sales region with the most sales
select * from #Product p
select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID
--combining
select
p.ID,
p.ProductName,
tp.Bestsale,
ps.SalesRegion
from
#Product p
inner join
(select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID
inner join
#ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number

Resources