I have 3 tables:
Accounts (fields used: ID varchar(20) and Name varchar(50))
OpttyPartner( fields used : ID15 varchar(20) , ACCOUNTTOID varchar(20)
Final2([Opportunity ID] varchar(20), Partner varchar(400)
I need to update Partner field of every record for final2 with name from accounts table.
Final2 is related to OpptyPartner with {opportunity ID] and ID15
Accounts is related with OpptyPartner with ID and ACCOUNTTOID
If there are more than one accounttoid for same Opportunity ID then the names should be appended and seperated with a ';'
For example:
Final2
ID Partner
1
OpptyPartner
ID15 ACCOUNTTOID
1 A1
1 A2
Accounts
ID Name
A1 ABC com
A2 EFG com
The output in Partner should be 'ABC com;EFG com'
How can this be achieved? Cursors ?
UPDATE:
;With partners as
(select * from Accounts inner join OpptyPartner on
Accounts.ID COLLATE Latin1_General_CS_AS=OpptyPartner.[ACCOUNTTOID] COLLATE Latin1_General_CS_AS
inner join Final2 on Final2.[Opportunity ID] = OpptyPartner.ID15)
Update Final2 set Partner = p.Names from
Final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.NAME as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY NAME
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on Final2.[Opportunity ID] = p.[Opportunity ID]
I think this might be of use:
;With partners as
(select [Opportunity ID], Name from accounts inner join OpttyPartner on
accounts.id=OpttyPartner.[ACCOUNTTOID]
inner join final2 on final2.[Opportunity ID] = OpttyPartner.id15)
Update final2 set partner = p.names from
final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.Name as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY Name
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on final2.[Opportunity ID] = p.[Opportunity ID]
Try using this (add collation where necessary) if you have multiple records in opptyPartner with same ID15 and ACCOUNTTOID :
;With partners as
(select [Opportunity ID], Name from accounts inner join (select distinct [ID15]
,[ACCOUNTTOID] from OpttyPartner) OpttyPartner on
accounts.id=OpttyPartner.[ACCOUNTTOID]
inner join final2 on final2.[Opportunity ID] = OpttyPartner.id15)
Update final2 set partner = p.names from
final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.Name as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY Name
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on final2.[Opportunity ID] = p.[Opportunity ID]
Related
I hope that someone from you will be able to help me as I got stuck with a (silly) condition logic.
I am joining 2 temp tables.
The target is to see the Jobs, Tracking numbers, etc. (all actions) in one row always for one Consignee (Consignee Ref). In other words, to show all actions/data per Consignee Ref.
The issue I got is duplacated values. The problem is that the Original Job (620X) field can have assigned Tracking_1 but it can be also null. Also the Second Job (629X) filed can have but do not need to have assigned the Tracking number/value. It can be also the case that both Tracking_1 and Tracking are NULL for one Consignee Ref.
When I would exclude Jobs where Tracking_1 or Tracking is NULL, then I will loose the Jobs that have no Tracking Numbers at all. So I used the code below, but then I am getting duplicates.
SELECT * FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
ORDER BY [Original Job (620X)] asc
How can I make it that I will get rid of the unnecessary duplicates (an example marked in red)?
And at the same time not to loose those jobs that have no Tracking Numbers?
I hope it makes sense.
Thank you very much in advance for any advise!
This is the entire code:
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp;
SELECT distinct
cne.[Consignee Ref],
s.[Trial AWB] as [Original Job (620X)],
rl.[CarrierReference] as [Tracking_1],
CAST(st.[Sched Collection date] as date) AS [Collection Date],
CAST(st.[Act Del Date] as date) AS [Delivery Date],
s.[Clientaccountcode] as [Account Code]
into #Temp
FROM MKN_Reporting.dbo.shipment AS s WITH (NOLOCK)
LEFT JOIN MKN_Reporting.dbo.[Lookup Month By JN Tb] AS b WITH (NOLOCK) ON s.[id] = b.[JobId]
LEFT JOIN MKN_Reporting.dbo.[Lookup Branch currency Tb] AS c WITH (NOLOCK) ON b.BranchPrefix = c.[Branch Prefix]
LEFT JOIN MKN_Reporting.dbo.[Lookup Client group Tb] AS g WITH (NOLOCK) ON s.[Clientaccountcode] = g.[Customer A/c]
LEFT JOIN MKN_Reporting.dbo.[Chargeto] AS cg WITH (NOLOCK) ON s.[id] = cg.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Shipper] AS sh WITH (NOLOCK) ON s.[id] = sh.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Cnee] AS cne WITH (NOLOCK) ON s.[id] = cne.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS r WITH (NOLOCK) ON sh.[Shipper Country code] = r.[Country Code]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS reg WITH (NOLOCK) ON cne.[Consignee Country code] = reg.[Country Code]
INNER JOIN MKN_Reporting.dbo.[Status] st ON COALESCE(s.ParentId, s.id) = st.Jobid
LEFT JOIN [CARRIERS_CHARGES] AS cc ON s.id = cc.JobId
LEFT JOIN [RouteLegs] as rl on cc.RouteLegId = rl.id
WHERE [Clientaccountcode] in ('US429', 'MI1091')
--AND rl.[CarrierReference] is not null
-------------------------------------------
IF OBJECT_ID('tempdb..#Temp2') IS NOT NULL
DROP TABLE #Temp2;
SELECT distinct
cne.[Consignee Ref],
s.[Study Number] as [Study_],
s.[Site Number] as [Site No_],
s.[Trial AWB] as [Second (629X)],
rl.[CarrierReference] as [Tracking],
CAST(st.[Sched Collection date] as date) AS [Collection Date],
CAST(st.[Act Del Date] as date) AS [Delivery Date],
s.[Clientaccountcode] as [Account Code]
into #Temp2
FROM MKN_Reporting.dbo.shipment AS s WITH (NOLOCK)
LEFT JOIN MKN_Reporting.dbo.[Lookup Month By JN Tb] AS b WITH (NOLOCK) ON s.[id] = b.[JobId]
LEFT JOIN MKN_Reporting.dbo.[Lookup Branch currency Tb] AS c WITH (NOLOCK) ON b.BranchPrefix = c.[Branch Prefix]
LEFT JOIN MKN_Reporting.dbo.[Lookup Client group Tb] AS g WITH (NOLOCK) ON s.[Clientaccountcode] = g.[Customer A/c]
LEFT JOIN MKN_Reporting.dbo.[Chargeto] AS cg WITH (NOLOCK) ON s.[id] = cg.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Shipper] AS sh WITH (NOLOCK) ON s.[id] = sh.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Cnee] AS cne WITH (NOLOCK) ON s.[id] = cne.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS r WITH (NOLOCK) ON sh.[Shipper Country code] = r.[Country Code]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS reg WITH (NOLOCK) ON cne.[Consignee Country code] = reg.[Country Code]
INNER JOIN MKN_Reporting.dbo.[Status] st ON COALESCE(s.ParentId, s.id) = st.Jobid
LEFT JOIN [CARRIERS_CHARGES] AS cc ON s.id = cc.JobId
left JOIN [RouteLegs] as rl on cc.RouteLegId = rl.id
WHERE [Clientaccountcode] in ('US1598')
--AND rl.[CarrierReference] is not null
---------------------------------------------
SELECT * FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
ORDER BY [Original Job (620X)] asc
I guess OP is looking for some kind of field aggregation for T2.
With SQL Server 2017+, like in PostgreSQL, you can now use STRING_AGG (same syntax than the Oracle LISTAGG.. "Why did they not use the same keyword...").
STRING_AGG will ignore null values from T2 and requires grouping if not alone. You have to add the other T1 and T2 required fields if any, but take care for T2 that it can imply duplicates and may need aggregation too...
Here is an example with your provided TSQL :
SELECT t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1],
STRING_AGG(t2.[Tracking],',') WITHIN GROUP (ORDER BY t2.[Tracking] ASC) Tracking_T2
FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
GROUP BY t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1]
ORDER BY t1.[Original Job (620X)] asc
EDIT: For previous SQL Server release (before 2017), you can achieve string aggregation with XML query :
EDIT2: Adding EXISTS clause to convey the INNER JOIN from the initial query.
SELECT t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1],
STUFF((SELECT ', ' + t2.[Tracking]
FROM #Temp2 t2
WHERE t1.[Consignee Ref] = t2.[Consignee Ref]
ORDER BY t2.[Tracking]
FOR XML PATH('')), 1, 1, N'') Tracking_T2
FROM #Temp t1
WHERE t1.[Tracking_1] is not null
AND EXISTS (SELECT DISTINCT 1 FROM #Temp2 t2 WHERE t2.[Consignee Ref] = t1.[Consignee Ref])
GROUP BY t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1]
ORDER BY t1.[Original Job (620X)] asc
I have a simple SQL query, with a handful of joined queries.
In my select I have a function shaping the date to a string format as below
LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
The script I am running should return 84 rows currently, but when executing the above in the select, it continuosly returns a different volume of rows every execution? there are no changes to the underlying tables between executions.
The strange thing is that whe I swith this back to a standard date conversion, the rows total 84
CONVERT(DATETIME,CONVERT(NVARCHAR,ADM_DT)+' '+ADM_TM)
Can anyone explain why SQL is behaving this way, I have not seen this before?
Full script below:
SELECT
[Visit ID] = a050.HSP_NO
,[Current Site] = currwd.HOSP
,[Current Specialty] = curr.SPEC
,[Current Ward] = currwd.WARD
,[Current Ward Name] = REPLACE(currwd.CURRDESC,'"','')
,[Current Consultant] = curr.PROF
,[Admission Date] = LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
,[Active] = '1'
,[PAS ID] = [crn].[crn]
,[Patient Class] = 'IP'
,NHS.[nhsno]
,CHI.CHI
,CASE WHEN OSV.X_CN IS NOT NULL THEN 'OSV' ELSE '' END OSV
,CASE WHEN NHS.[nhsno] LIKE '7%' THEN '7 NHSNO' ELSE '' END [PROBLEM NHS NO]
,DATEDIFF(D,PATS.DATE_OF_BIRTH,CONVERT(DATE,ADM_DT)) /365 [AGE ON ADMISSION]
FROM PCSSSA..SILVER.APK050_HPROVSPELL a050 WITH (NOLOCK)
-- Current Admission details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, SPEC, PROF --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)curr
ON curr.X_CN = a050.X_CN
AND a050.HSP_NO = curr.HSP_NO
AND curr.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO DESC)
-- Current Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN, CEP_NO ORDER BY WS_NO DESC) AS WR
FROM PCSSSA..SILVER.APK052_WARDSTAY wdstay WITH (NOLOCK)
LEFT JOIN (SELECT
CURRWARD = OBJ_LOC,
CURRDESC = OBJ_DESC
FROM [PCSSSA]..[SILVER].[ENV030_LOCDETS] WITH (NOLOCK)
WHERE OBJ_TYPE = 'WARD'
AND DATE_TO IS NULL
)wdname
ON wdstay.WARD = wdname.CURRWARD
) currwd
ON curr.X_CN = currwd.X_CN
AND curr.CEP_NO = currwd.CEP_NO
AND currwd.WR=1
--- Admitting details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, PROF, SPEC --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)adm
ON adm.X_CN = a050.X_CN AND a050.HSP_NO = adm.HSP_NO
AND adm.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO)
-- Admitting Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN,CEP_NO ORDER BY WS_NO) AS WR FROM PCSSSA..SILVER.APK052_WARDSTAY WITH (NOLOCK)) admwd
ON adm.X_CN = admwd.X_CN
AND adm.CEP_NO = admwd.CEP_NO
AND admwd.WR=1
-- Patient Detail
LEFT JOIN
(SELECT
[id].[RM_PATIENT_NO],
[id].[NUM_ID_TYPE] + CONVERT(NVARCHAR,[NUMBER_ID]) [crn]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('0', '1', 'W')
)[crn]
ON a050.[X_CN] = [crn].[RM_PATIENT_NO]
-- NHS NUMBERS
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [nhsno]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] = ('NHS')
)NHS
ON NHS.RM_PATIENT_NO = a050.X_CN
-- CHI NUMBER
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [CHI]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('CHI')
)CHI
ON CHI.RM_PATIENT_NO = a050.X_CN
-- OVERSEES STATUS
LEFT JOIN
(
SELECT X_CN, [STATUS], SDATE, EDATE FROM PCSSSA..SILVER.CRS037_OSV_STATUS WITH (NOLOCK)
)OSV
ON OSV.X_CN = a050.X_CN
AND CONVERT(DATE,ADM_DT) >= OSV.SDATE
AND (OSV.SDATE IS NULL
OR CONVERT(DATE,ADM_DT) <= OSV.EDATE)
-- DEMOGRAPHICS
LEFT JOIN
(
SELECT RM_PATIENT_NO, DATE_OF_BIRTH FROM PCSSSA..[SILVER].[PATIENTS] WITH (NOLOCK)
)PATS
ON PATS.RM_PATIENT_NO = a050.X_CN
-- CURRENTLY ADMITTED ONLY
WHERE DIS_DT IS NULL
-- WITHOUT NHS NUMBER
AND (nhsno IS NULL
-- OR BRING IN ANY 7 NHS NUMBERS FOR CORRECTION
OR NHS.[nhsno] LIKE '7%'
-- ALSO INCLUDE OVERSEES
OR OSV.X_CN IS NOT NULL)
What is even stranger, is that if you wrap this in a subquery and coun(*) on the outer then it totals 84 as expected, very strange!
We have a table with the following information:
Account ID, Touch Number, Type, Touch Date, and Stage (ranked 1-3, 1 if touch number < 50, 2 if 51-100, 3 if > 100).
Screenshot from table
I am looking to write a query that captures the type with the most touches at each stage for each account, looking something like this:
Output I am looking to receive
Here is the current query I wrote that is not working for me:
`SELECT distinct
a.[Account ID],
a.Stage,
bb.Stage1TopType,
bb.TypeCount_1,
c.Stage2TopType,
c.TypeCount_2,
d.Stage3TopType,
d.TypeCount_3
FROM SFAX.dbo.LinearTest as a
--STAGE 1
LEFT JOIN
(
SELECT
a.[Account ID],
a.Type as Stage1TopType,
Max(b.TouchCount) as TypeCount_1
FROM SFAX.dbo.LinearTest as a
LEFT JOIN
(
SELECT
[Account ID],
Type,
COUNT(TouchNumber) as TouchCount
FROM SFAX.dbo.LinearTest
WHERE Stage = 1
GROUP BY [Account ID], Type
) as b on a.[Account ID] = b.[Account ID]
WHERE a.Stage = 1
GROUP BY a.[Account ID], a.Type
) as bb on a.[Account ID] = bb.[Account ID]
--STAGE 2
LEFT JOIN
(
SELECT
a.[Account ID],
a.Type as Stage2TopType,
Max(b.TouchCount) as TypeCount_2
FROM SFAX.dbo.LinearTest as a
LEFT JOIN
(
SELECT
[Account ID],
Type,
COUNT(TouchNumber) as TouchCount
FROM SFAX.dbo.LinearTest
WHERE Stage = 2
GROUP BY [Account ID], Type
) as b on a.[Account ID] = b.[Account ID]
WHERE a.Stage = 2
GROUP BY a.[Account ID], a.Type
) as c on a.[Account ID] = c.[Account ID]
--STAGE 3
LEFT JOIN
(
SELECT
a.[Account ID],
a.Type as Stage3TopType,
Max(b.TouchCount) as TypeCount_3
FROM SFAX.dbo.LinearTest as a
LEFT JOIN
(
SELECT
[Account ID],
Type,
COUNT(TouchNumber) as TouchCount
FROM SFAX.dbo.LinearTest
WHERE Stage = 3
GROUP BY [Account ID], Type
) as b on a.[Account ID] = b.[Account ID]
WHERE a.Stage = 3
GROUP BY a.[Account ID], a.Type
) as d on a.[Account ID] = d.[Account ID]
`
Please let me know if you have any suggestions on how I can receive my desired output.
I believe a simple ROW NUMBER window function should be enough.
;WITH MostTouchesByAccountStage AS
(
SELECT
T.[Account ID],
T.Stage,
T.TouchNumber,
T.Type,
T.TouchDate,
Ranking = ROW_NUMBER() OVER ( -- Generate a ranking
PARTITION BY
T.[Account ID], -- That will reset with each different value of Account and Stage
T.Stage
ORDER BY
T.TouchNumber DESC) -- And is ordered by TouchNumber descendently
FROM
YourTable AS T
)
SELECT
T.*
FROM
MostTouchesByAccountStage AS T
WHERE
T.Ranking = 1
What I am looking for is the Type that appears the greatest number of
times in each stage.
You will need to perform the count first, then decide which of these has the highest value. Below you will see the count performed in a "derived table", then row_number() is used to assign a value of 1 to the highest count, and finally we only return te rows with that value of 1
SELECT
[Account ID]
, Stage
, TouchNumber
, Type
, TouchDate
, type_count
FROM (
SELECT
[Account ID]
, Stage
, TouchNumber
, Type
, TouchDate
, type_count
, ROW_NUMBER() OVER (PARTITION BY [Account ID], Stage ORDER BY type_count DESC, Type) AS rn
FROM (
SELECT
[Account ID]
, Stage
, TouchNumber
, Type
, TouchDate
, COUNT( * ) OVER (PARTITION BY [Account ID], Stage, Type) AS type_count
FROM YourTable AS T
) sq
) d
WHERE rn = 1
ORDER BY
[Account ID]
, Stage
nb. there might be more than one row with the same high value but only one row can be returned, if you want more then one row with for a tie use dense_rank() instead
I have a query that works really well. But I am trying to add a filter so if users_in_this_country is > 1. I know to add users_in_this_country > 1 to the WHERE. But if I add it inside the parenthesis it says invalid column and the same if I add it outside of the parenthesis. This is probably really dumb and easy, but what am I over looking? Thanks!
SELECT u.ContactName
,cu.[User ID]
,c.Name
,c.ID
,cu.[Foreign Table]
,count(*) OVER (PARTITION BY c.ID) AS user_in_this_country
FROM dbo.Country AS c
INNER JOIN dbo.CountryUser AS cu ON c.ID = cu.[Foreign ID]
INNER JOIN dbo.UserColder AS u ON cu.[User ID] = u.ID
WHERE EXISTS (
SELECT *
FROM CountryUser AS cu2
WHERE cu2.[Foreign ID] = cu.[Foreign ID]
AND cu2.[User ID] <> cu.[User ID]
AND cu.[Foreign Table] = 'Country')
The reason you can't refer to it in the WHERE clause is that its very meaning, for a given row, depends on what other rows satisfy the WHERE clause; so it would all be too circular.
The simplest fix is to wrap your entire query in SELECT * FROM ( ... ) t WHERE t.user_in_this_country > 1.
That said, it seems like your query already ensures that user_in_this_country > 1, by virtue of the EXISTS clause, which makes sure that there exists a different CountryUser record that belongs to the same Country and a different User. What am I missing?
With aggregate functions (like COUNT) used in conjuction with OVER clause you have to use a CTE or a subquery, like this
WITH CTE AS (
SELECT u.ContactName
,cu.[User ID]
,c.Name
,c.ID
,cu.[Foreign Table]
,count(*) OVER (PARTITION BY c.ID) AS user_in_this_country
FROM dbo.Country AS c
INNER JOIN dbo.CountryUser AS cu ON c.ID = cu.[Foreign ID]
INNER JOIN dbo.UserColder AS u ON cu.[User ID] = u.ID
WHERE EXISTS (
SELECT *
FROM CountryUser AS cu2
WHERE cu2.[Foreign ID] = cu.[Foreign ID]
AND cu2.[User ID] <> cu.[User ID]
AND cu.[Foreign Table] = 'Country')
)
SELECT *
FROM CTE
WHERE user_in_this_country > 1
Because "users_in_this_country" is not a column, it is an alias which is not valid in the scope of the WHERE clause. I 'm not familiar with "OVER" or PARTITION BY but, my guess is you'd have to do something like this:
WHERE blabla AND (count(*) OVER (PARTITION BY c.ID)) > 1
I need to return only the names that have more than one franchise. I can get a list with everyone and i can get a list of all the names that have more than one but i am unable to have that list show multiple rows with the name in each i only get one row with the name and the count of how many times it is in there. here is the code i have I am using a SQL Server the Xref table look like this
fraID|memERBCode|GLLevel|customerNumber|vendorNumber|DAVendorNumber|DAVindoeDisabled|status|di|ctyID
145 145 145 144020145 02PF0145 02DA0145 1 I WI 1
146 146 146 144020146 02PF0146 02DA0146 0 I 3F 1
.
select [Last Name],[First Name], count(*)
from(
SELECT
conLastName as [Last Name],
conFirstName as [First Name],
conMiddleInitial as [Middle Initial],
lawsonXRef.memERPCode as [Franchise],
contactType.ctpDisplayName as [Type],
contactStatus.ctpDisplayName as [Status]
FROM Contacts
inner join lawsonXRef
on lawsonXRef.fraID = Contacts.fraID
inner join SalesRepresentatives
on Contacts.conID = SalesRepresentatives.conID
inner join CategoryPopulation contactType
on contactType.ctpID = Contacts.conTypeId
inner join CategoryPopulation contactStatus
on contactStatus.ctpID = Contacts.conStatusId
WHERE
srActive = 1 -- is Sales Rep.
and
(Contacts.conLastName <> '' and Contacts.conFirstName <> '')
)data1
group by [Last Name],[First Name]
having count(*)>1
order by [Last Name]
It looks as though your contact table will hold multiple records for a single contact - one for each franchise.
If so, the following should work:
SELECT con.conLastName as [Last Name],
con.conFirstName as [First Name],
con.conMiddleInitial as [Middle Initial],
lawsonXRef.memERPCode as [Franchise],
contactType.ctpDisplayName as [Type],
contactStatus.ctpDisplayName as [Status]
FROM (select conLastName, conFirstName, conMiddleInitial
from Contacts
group by conLastName, conFirstName, conMiddleInitial
having count(distinct fraID) > 1) con
inner join Contacts
on con.conLastName = Contacts.conLastName and
con.conFirstName = Contacts.conFirstName and
con.conMiddleInitial = Contacts.conMiddleInitial
inner join lawsonXRef
on lawsonXRef.fraID = Contacts.fraID
inner join SalesRepresentatives
on Contacts.conID = SalesRepresentatives.conID
inner join CategoryPopulation contactType
on contactType.ctpID = Contacts.conTypeId
inner join CategoryPopulation contactStatus
on contactStatus.ctpID = Contacts.conStatusId
WHERE
srActive = 1 -- is Sales Rep.
and
(Contacts.conLastName <> '' and Contacts.conFirstName <> '')
Incidentally, if this is your design then I strongly recommend changing it. What if there are several people called Jane Smith?
You can look at doing something like a derived table in your query that only returns the id of people with multiple franchises.
Guessing at your query, if a Contact exists in lawsonXref more than once, that's considered having muliple franchises. fraID is franchise id and that uniquely identifies a franchise?
SELECT
conLastName as [Last Name],
conFirstName as [First Name],
conMiddleInitial as [Middle Initial],
lawsonXRef.memERPCode as [Franchise],
contactType.ctpDisplayName as [Type],
contactStatus.ctpDisplayName as [Status]
FROM
Contacts
inner join
(
-- this should generate a list of all
-- the franchise ids that exist more than
-- once in the xref table
SELECT
X.fraID
FROM
lawsonXRef X
GROUP BY
X.fraID
HAVING
count(1) > 1
on lawsonXRef.fraID = Contacts.fraID
) AS lawsonXRef
inner join
SalesRepresentatives
on Contacts.conID = SalesRepresentatives.conID
inner join
CategoryPopulation contactType
on contactType.ctpID = Contacts.conTypeId
inner join
CategoryPopulation contactStatus
on contactStatus.ctpID = Contacts.conStatusId
WHERE
srActive = 1 -- is Sales Rep.
and
(Contacts.conLastName <> ''
and Contacts.conFirstName <> '')
if that's not working, provide a few rows of LawsonXref data showing an example of a single franchise record and one with multiple.