0

I have data like this I have data like this

I want to count edit: distinct group1 and group 2 group by the Time and Type. I make each a temporary table then full outer join (on time and type) so desire column like:

Time    Type    Count_Group1     Count_Group2

Any shorter way to do this?

3
  • Sample data is better presented as formatted text. See here for some tips on how to create nice looking tables. Commented Sep 1, 2020 at 16:26
  • @a_horse_with_no_name thank you, because im using mobile to write this questions Commented Sep 1, 2020 at 16:32
  • Before anything, consider re-factoring your table design for a normalized framework. You avoid complex querying in doing so. Columns and tables with numbered suffixes are usually sub-optimal schema. Aim for long not wide tables. Commented Sep 1, 2020 at 16:48

1 Answer 1

1

This answers the original version of the question:

You can use a lateral join and aggregation:

select time, type, sum(in1), sum(in2)
from t cross join lateral
     (values (time1, group1, 1, 0), (time2, group2, 0, 1)
     ) v(time, grp, in1, in2)
group by time, type;

EDIT:

To count distinct values, use count(distinct):

select v.time, t.type, count(distinct t.group1), count(distinct t.group2)
from t cross join lateral
     (values (t.time1), (time2)
     ) v(time)
group by v.time, t.type;
Sign up to request clarification or add additional context in comments.

9 Comments

I want each column for group 1 and group 2 count. Why there is a grp column? @gordon
@HaoHao . . . Good point. grp is not needed. I removed it.
there is still 'grp' above, I replace that with 'type' my code say type is ambiguous, I didn't know about this type of join yet. @gordon
what is in1 and in2?
1,0 and 0,1 also I hope you could explain more @gordon
|

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.