I have a sample table, called [SAMPLES] which I've added multiple columns to the end for different types of lab analysis results, however for the majority of samples only one analysis has been completed. I want to be able select only the samples where more than one analysis has been completed on the same sample.
The table structure is something like:
For the above, the query should select only samples 'ABC122' and 'ABC123'.
Is there an easy way to select this data out?
You can use cross apply
and values
to easily unpivot your columns back into the rows they should be, then count and filter accordingly
with x as (
select distinct sampleId, SampleType, Count(*) over(partition by sampleid,sampletype) qty
from samples s
cross apply(values (analysis1),(analysis2),(analysis3),(analysis4),(analysis5),(analysis6))v(analysis)
where analysis is not null
)
select s.*
from x join samples s on s.sampleid=x.sampleid and s.sampletype=x.sampletype
where x.qty>1
A better database design would be:
samples table
-------------
sampleID
sampleType
analyses table
--------------
sampleID
analysisType
analysisResult
Then you can query your desired result like this:
select sampleID
from analyses
group by sampleID
having count(analysisResult) >= 2
With proper indexes this will be super fast.
You can go for UNPIVOT to get the sampleids with analysis > 1. then use those sampleids for filtering.
--
DECLARE @sample table(sampleid char(30), sampletype char(10), analysis1 decimal(3,2),analysis2 decimal(3,2), analysis3 decimal(3,2), analysis4 decimal(3,2))
insert into @sample
values ('ABC121','ROCK',0.23,null,null,null),('ABC122','ROCK',0.27,null,null,0.23),('ABC123','ROCK',0.22,null,null,0.28),
('ABC124','ROCK',null,null,0.25,null)
;WITH CTE_Moresamples as
(
SELECT sampleid FROM @sample
unpivot
(
val for keyv in ([analysis1],[analysis2],[analysis3],[analysis4])
) as upvt
group by sampleid
having count(val) > 1
)
SELECT * FROM @sample as s
inner join CTE_Moresamples as c
on c.sampleid = s.sampleid
sampleid | sampletype | analysis1 | analysis2 | analysis3 | analysis4 |
---|---|---|---|---|---|
ABC122 | ROCK | 0.27 | NULL | NULL | 0.23 |
ABC123 | ROCK | 0.22 | NULL | NULL | 0.28 |
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.