1

I have 3 tables scan_1, scan_2, scan_3. Here is structure of SQL schema:

scan_1:                 scan_2:                   scan_3:
P_no work               P_no work                 P_no work
1    YES                1    YES                  1    NO
2    NO                 2    NO                   2    NO
3    YES                3    YES                  3    NO

I want to count P_no where work ='YES'. But if yes occurred in 2 position LIKE for P_no = 1 which having YES in scan_1 and scan_2 it must be count as 1.

my query is :

SELECT count(`P_no`) AS `ab1` FROM 
`scan_1`,`scan_2`,`scan_3` WHERE 
((`scan_1`.`work`= 'YES') OR 
(`scan_2`.`work`= 'YES') OR 
(`scan_3`.`work`= 'YES')) 

4 Answers 4

1

TRY THIS:

SELECT COUNT(*) AS total_count 
FROM
    (
        SELECT P_no, work FROM scan_1 WHERE work = 'YES'
        UNION
        SELECT P_no, work FROM scan_2 WHERE work = 'YES'
        UNION
        SELECT P_no, work FROM scan_3 WHERE work = 'YES'
    ) AS total
Sign up to request clarification or add additional context in comments.

Comments

1

You can achieve your desired result using UNION like below :

SELECT COUNT(*) AS ab1
FROM (
    SELECT P_no, work FROM scan_1 WHERE work='YES'
    UNION
    SELECT P_no, work FROM scan_2 WHERE work='YES'
    UNION
    SELECT P_no, work FROM scan_3 WHERE work='YES'
) as T

SQL HERE

Notice the three queries which is merged using UNION. It merges the result and excludes the duplicate records from the result.

Comments

1

This may work for you as far I understood. Using union for eliminating duplicates.

    select count(*) AS `ab1` FROM
    (
    select `P_no`,`work` from `scan_1` s1 where `work`= 'YES' 
     union
    select `P_no`,`work` from `scan_2` s2 where `work`= 'YES'
     union
     select `P_no`,`work` from `scan_3` s3 where `work`= 'YES' 
    ) as final

2 Comments

Error : check the manual for the right syntax to use near 'as one union
Sorry MySql is not current installed on my pc. Can you check the edit again?
0

Try this,

SELECT COUNT(DISTINCT P_No) AS ab1
FROM (
    SELECT P_no, work FROM scan_1
    UNION
    SELECT P_no, work FROM scan_2
    UNION
    SELECT P_no, work FROM scan_3
) T
WHERE T.Work='YES'

Hope this helps you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.