Ask Ben: Querying Groups With Conditional Elements

<!--- Query for TransID values. --->
<cfquery name="qStrict" datasource="#REQUEST.DSN.Source#">
	<!--- Build SQL table and populate. --->
	#PreserveSingleQuotes( strBuildSQL )#
 
 
	<!--- Get the appropriate trans IDs. --->
	SELECT
		d.trans_id
	FROM
		@data d
	GROUP BY
		d.trans_id
	HAVING
 
		<!---
			Make sure that the group has either
			tag ID 1 or 4.
		--->
		COUNT(
			CASE
				WHEN
					d.tag_id IN ( 1,4 )
				THEN
					d.tag_id
				ELSE
					NULL
			END
		) > 0
	AND
		<!---
			Make sure that the group does not also contain
			the tag id, 2.
		--->
		COUNT(
			CASE
				WHEN
					d.tag_id = 2
				THEN
					d.tag_id
				ELSE
					NULL
			END
		) = 0
	;
</cfquery>
 
 
<!--- Output out results. --->
TransID: #ValueList( qStrict.trans_id, ', ' )#

For Cut-and-Paste