• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 197
  • Last Modified:

SQL Server CTE

I need to find using a CTE all Providers that belong to Multiple provider groups and I'm having a difficult time doing so.

Here's how I'd like for this to work. Find a provider, if the provider belongs to one group, show it. If the provider belongs to multiple groups, then update all of the provider groups for this provider to null.

WITH theResultSet AS
(
    SELECT DISTINCT(ProviderKey) AS col1 FROM ##tmpProviderGrp_RAMember
)
SELECT a.ProviderGroupKey
  FROM ##tmpProviderGrp_RAMember AS a
  JOIN ##tmpProviderGrp_RAMember as b ON a.ProviderKey = b.ProviderKey
)
update cte
set IDA_ProviderGroupKey= NULL
WHERE cnt > 1;
0
SharonBernal
Asked:
SharonBernal
  • 2
  • 2
3 Solutions
 
lcohanDatabase AnalystCommented:
--Is this what you mean and need?

WITH cte_ResultSet AS
(
SELECT count(DISTINCT ProviderKey) as num, ProviderKey FROM ##tmpProviderGrp_RAMember
group by ProviderKey
)

SELECT a.ProviderGroupKey, case when cte.num > 1 then null else cte.num end as num, cte.ProviderKey
FROM ##tmpProviderGrp_RAMember a
   INNER JOIN cte_ResultSet cte ON a.ProviderKey = cte.ProviderKey
0
 
SharonBernalAuthor Commented:
This is close, I've looked at it. It does not set the ProviderGroupKey to null in the table. There needs to be an update. The results look like below, the ProviderKey is in two groups, so the ProviderGroupKey needs to be set to null.

ProviderGroupKey      num      ProviderKey
xxxxx90004      NULL      CCC72237
xxxxx90004      NULL      CCC72237
xxxxx90004      NULL      CCC72237
xxxxx80004      NULL      CCC72237
xxxxx80004      NULL      CCC72237
xxxxx80004      NULL      CCC72237
0
 
SharonBernalAuthor Commented:
Also, on the example above the num should be 2. There are two groups with the same provider.
0
 
lcohanDatabase AnalystCommented:
Argh...I thought you had that just in the CTE for whatever reason so you can get the record set:
...
 update cte
 set IDA_ProviderGroupKey= NULL
 WHERE cnt > 1;
...

well in that case you can use the SELECT as a source to either populate a #TEMP table and then update the permanent table from it matching by the ProviderKey or just in a subquery
0
 
John_VidmarCommented:
UPDATE	a
SET	IDA_ProviderGroupKey = NULL
FROM	##tmpProviderGrp_RAMember	a
JOIN	(	SELECT	ProviderKey
		FROM	##tmpProviderGrp_RAMember
		GROUP
		BY	ProviderKey
		HAVING	COUNT(DISTINCT ProviderGroupKey) > 1
	) b	ON	a.ProviderKey = b.ProviderKey

Open in new window

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now