I’m writing some SQL for our lab, and I have it all done except for the fact that I need to count the DISTINCT number of samples that get returned. Here is the working code without COUNT() incorporated. It ties together three tables. When I use a COUNT() function, I get inaccurate results. Do I need to incorporate a subquery in SELECT?
SELECT
batchid,
s_sampleid,
requestid,
u_labinstance,
sdiworkitem.workitemid,
workitemdesc
FROM s_sample INNER JOIN (sdiworkitem INNER JOIN workitem ON sdiworkitem.workitemid = workitem.workitemid)
ON s_sample.s_sampleid = sdiworkitem.keyid1
GROUP BY
s_sampleid,
batchid,
requestid,
u_labinstance,
sdiworkitem.workitemid,
workitemdesc
UPDATE (Working Query)
SELECT
batchid,
COUNT(DISTINCT s_sampleid),
s_sampleid,
requestid,
u_labinstance,
sdiworkitem.workitemid,
workitemdesc
FROM s_sample INNER JOIN (sdiworkitem INNER JOIN workitem ON sdiworkitem.workitemid = workitem.workitemid)
ON s_sample.s_sampleid = sdiworkitem.keyid1
GROUP BY
batchid,
requestid,
u_labinstance,
sdiworkitem.workitemid,
workitemdesc
First, take out s_sampleid from the GROUP BY
Then, try both of these
The GROUP BY on s_sampleid will always give “1” so fix that, then see which of these COUNTs is correct.
Edit:
If you need the actual s_sampleid and the count, then you need the OVER clause and remove the GROUP BY
This should work… otherwise it’s a sub query
Otherwise, you should have mentioned you want the values and the count at the start