0

I'm newbie in MYSQL.

I have a table like below:


colmnA    colmnB
A           x
A           y
B           x
B           z
C           x
D           null

What I want to achieve is something like:

SELECT
COUNT(distinct colmnA) WHERE colmnB IS NOT NULL AS deployed,
COUNT(distinct colmnA) WHERE colmnB IS NULL AS undeployed
FROM table

which will be resulted in:

deplyed    undeployed
3          1

is there an elegant way to achieve this with a single query? thanks for help

As far as I've searched, the most closed solution is combining SUM() with CASE condition, ex:

SELECT SUM(CASE WHEN columnB IS NOT NULL then 1 else 0) AS deployed

but it will include duplicated count, and there is no way to add DISTINCT into SUM().

2 Answers 2

1

Why not use count?

SELECT COUNT(DISTINCT CASE WHEN colmnB IS NOT NULL THEN colmnA END) deployed,
       COUNT(DISTINCT CASE WHEN colmnB IS NULL THEN colmnA END) undeployed
FROM   table;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! it's working! and I apologies for my poor searching skill -_-
0

select max(deployed) as deployed, max(undeployed) as undeployed from ( select count(distinct columnA) as deployed, 0 as undeployed from testtable where columnb is not null union select 0 as deployed, count(distinct columnA) as undeployed from testtable where columnb is null ) as foo;

@JRD's answer works too.

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.