Link to home
Start Free TrialLog in
Avatar of Nate_LR
Nate_LR

asked on

sql count distinct for total column

I'm trying to create a box total column in a table by counting distinct cases from multiple columns in the same table.  I can do this properly when the box total column is in another table, but I can't figure out the self-join or whatever is required when it's in the same table.
UPDATE tblWhCoreBoxTotal
SET BoxTotal = 

(SELECT COUNT(*)
FROM 
(SELECT DISTINCT f_WellLocationID, AGS_ID, BOX_NUM, WH_LOCATION, f_SAMPLETYPEID
FROM tblWhCoreSample
WHERE tblWhCoreSample.f_WellLocationID = tblWhCoreBoxTotal.f_WellLocID
AND tblWhCoreSample.AGS_ID = tblWhCoreBoxTotal.AGS_ID
   ) t
 )

Open in new window

Avatar of lcohan
lcohan
Flag of Canada image

You need to put a distinct col_name in the count like below but it also needs to have distinct values for sure. If not you could add a relative record number to your subquery and count on that field:

UPDATE tblWhCoreBoxTotal
SET BoxTotal =

(SELECT COUNT(distinct f_WellLocationID)
FROM
(SELECT DISTINCT f_WellLocationID, AGS_ID, BOX_NUM, WH_LOCATION, f_SAMPLETYPEID
FROM tblWhCoreSample
WHERE tblWhCoreSample.f_WellLocationID = tblWhCoreBoxTotal.f_WellLocID
AND tblWhCoreSample.AGS_ID = tblWhCoreBoxTotal.AGS_ID
   ) t
 )
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nate_LR
Nate_LR

ASKER

Thank-you so much!