Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I have been tasked with identifying invoices where a series of CPT (Test Codes) are present. For example below are a list of invoices if I want to identify invoices where both 88305 and 88306 exist on the same invoice how would I do that using T-SQL?
Select INVOICE from yourtablegroup by INVOICEhaving count(case CPT when 88305 or 88306 then 1 else 0 end)=2I havent tested it on a real tablePBUH
Ifor
Aged Yak Warrior
700 Posts
Posted - 2011-01-12 : 08:19:39
I think Sachin's version should use SUM and not COUNT.You could also try the following:
SELECT InvoiceFROM InvoicesWHERE CPT in (88305, 88306)GROUP BY InvoiceHAVING COUNT(*) = 2-- or;WITH InvCntsAS(SELECT Invoice, CPT ,SUM(CASE WHEN CPT in (88305, 88306) THEN 1 ELSE 0 END) OVER (PARTITION BY Invoice) AS InvCntFROM Invoices)SELECT Invoice, CPTFROM InvCntsWHERE InvCnt = 2
Sachin.Nand
2937 Posts
Posted - 2011-01-12 : 08:21:03
quote:I think Sachin's version should use SUM and not COUNT.
Yes you are right.Thanks for the catch.PBUH
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2011-01-12 : 08:56:50
[code]Select INVOICE from yourtableWHERE CPT in (88305, 88306) group by INVOICEHAVING MIN(CPT) <> MAX(CPT)[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/
bconner
Starting Member
48 Posts
Posted - 2011-01-12 : 09:03:18
Thanks Sachin.Nand and IFor for your help, I have been racking my brains trying to figure out.Brian