1

I need a Postgresql Query that returns the count of every type of combination of record.

For example, I have a table T with columns A, B, C, D, E and other columns that are not of importance:

Table T
--------------
A | B | C | D | E

The query should return a table R with the values from columns A, B, C, D, and a count for how many times each configuration occurs with the specified E value.

Table R
---------------
A | B | C | D | count

When all of the counts for each record are added together, it should equal the total number of records in the original table.

It seems like a very simple problem, but due to my lack of SQL knowledge, I cannot figure out how to do this.

The only solution I can think of is this:

select a, b, c, d, count(*)
  from T
  where e = 'abc'
  group by a, b, c, d

But when adding the counts up from this query, it is way more than the count of the original table. It seems like count(*) shouldn't be used, or i'm just totally going about this the wrong way. I'd really appreciate any advice as to how I should go about this. Thank you all.

2
  • 2
    Maybe you are fooled by NULLs? please show us some data. Aug 6, 2012 at 21:47
  • 1
    I agree with @wildplasser - what you're showing us should work fine. So the problem lies somewhere in what you're not showing us yet.
    – kgrittn
    Aug 6, 2012 at 21:52

2 Answers 2

0

NULL values couldn't possibly fool you. Consider this demo:

WITH t(a,b,c,d) AS (
    VALUES
     (1,2,3,4)
    ,(1,2,3,NULL)
    ,(2,2,3,NULL)
    ,(2,2,3,NULL)
    ,(2,2,3,4)
    ,(2,NULL,NULL,NULL)
    ,(NULL,NULL,NULL,NULL)
    )
SELECT a, b, c, d, count(*)
FROM   t
GROUP  BY a, b, c, d
ORDER  BY a, b, c, d;

 a | b | c | d | count
---+---+---+---+-------
 1 | 2 | 3 | 4 |     1
 1 | 2 | 3 |   |     1
 2 | 2 | 3 | 4 |     1
 2 | 2 | 3 |   |     2
 2 |   |   |   |     1
   |   |   |   |     1

There must be some other misunderstanding here.

0
0

I figured it out, it was something really stupid. I forgot to specify the where 'E' = 'ABC' clause in the select count(*) when comparing the count. Thanks anyway for your help guys!

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.