2

So I'm trying to get 2 sets or results from the same table grouped by a 3rd column, it's best i let my example explain;

SELECT
  (SELECT COUNT(DISTINCT id)
  FROM Database
    WHERE Status NOT LIKE 'closed') AS ColumnA,

  (SELECT COUNT(DISTINCT id)
  FROM Database
    WHERE Status NOT LIKE 'closed' AND Datevalue <= getdate()) AS ColumnB

Group By ColumnC

Now I know this wont/doesn't work but it explains what I want. If I leave the group by out then i get the figures as a whole but i want them grouping by another Column.

Mind is melting, ready to be enlightened.

1
  • This answer might be more along the lines of what you're looking for as opposed to nesting SELECT statements you can do a COUNT(DISTINCT...) with conditionals sql- COUNT DISTINCT with CONDITION
    – vielkind
    Jun 1, 2018 at 16:28

2 Answers 2

2

Is this what you want?

select columnC,
       count(distinct case when Status <> 'closed' then id end) as columnA,
       count(distinct case when Status <> 'closed' and datevalue <= getdate() then id end) as columnb
from database  -- a very curious name for a table
group by ColumnC;
1
  • You sir, are a savour, I've been banging my head for close to an hour. thank you! I shall now study this to ensure i understand it for future use. cheers.
    – Paul
    Jun 1, 2018 at 16:21
0

Try this

    SELECT ColumnC,
    COUNT(DISTINCT CASE WHEN Status NOT LIKE 'closed' THEN id END) as  ColumnA,
    COUNT(DISTINCT CASE WHEN Status NOT LIKE 'closed' AND  Datevalue <= getdate() THEN id END) as  ColumnB
    FROM mydatabase
    GROUP BY ColumnC

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.