-1

I am having a hard time to write the SQL query to do

something like, how many distinct record on column B for each record on Column A

Let's say: Column A,,,,,,,,,,,,,,,,, Column B

             A                   1

             A                   1      would return 3 for A (3 distinct records 1,2,3)

             A                   2

             A                   3

             B                   4      Would return 2 for B (4,5)

             B                   4

             B                   5

             C                   6      Would return 1 for C

             C                   6

it will be imported to a datagridview to show the result

Column 1---------------Column 2

   A                   3

   B                   2

   C                   1

column 2 being the result of the query

I don't know if it is easy and I don't get it or complicated but I can't figure out.

I have tried Group By, Distinct etc... I get either not what I want or error like no value given....

Thank you.

After some research I found this query that seems to return the results expected.

SELECT ColA, COUNT(COLB) FROM (SELECT ColA, ColB FROM Table Where blablabla GROUP BY ColA,ColB) GROUP BY ColA"

ekad
  • 14,436
  • 26
  • 44
  • 46
Julien7377
  • 475
  • 4
  • 15
  • Welcome to StackOverflow! Looks like you have found the answer yourself. Please move the part from `After some research ....` to [your own answer below](http://stackoverflow.com/a/41205521/1905949) and mark your answer as accepted. Answers shouldn't be in the question. – ekad Jan 08 '17 at 02:00

3 Answers3

0

You could try something like:

SELECT ColA, Count(ColB)
FROM MyTable (NOLOCK)
GROUPBY ColA
0

The sql query is select colA, colB, COUNT(DISTINCT colB) from t1 group by colA

You can access in SQL fiddle.

http://sqlfiddle.com/#!9/2c84d8/7

Senthil
  • 2,156
  • 1
  • 14
  • 19
0

Actually, if what you're looking to partition the counts try: over (Partition by)

Partition Function COUNT() OVER possible using DISTINCT

Community
  • 1
  • 1