0

I'm quite new to SQL and coding generally.

I have a SQL query that works fine. All I want to do now is return the number of rows from that query result.

The current SQL query is:

SELECT 
    Progress.UserID, Questions.[Question Location],
    Questions.[Correct Answer], Questions.[False Answer 1],
    Questions.[False Answer 2], Questions.[False Answer 3]
FROM
    Questions 
INNER JOIN
    Progress ON Questions.[QuestionID] = Progress.[QuestionID]
 WHERE 
    (((Progress.UserID) = 1) AND 
     ((Progress.Status) <> "Correct")
    );

I know I need to use

SELECT COUNT(*)

...though not quite sure how I integrate it into the query.

I then intend to use OLEDB to return the result to a VB Windows Form App.

All help is much appreciated.

Thanks! Joe

T.S.
  • 18,195
  • 11
  • 58
  • 78
Joe Jones
  • 13
  • 1
  • 6

3 Answers3

3

To count all of the records, use a simple subquery; subqueries must have aliases (here I've named your subquery 'subquery').

SELECT COUNT(*) 
FROM (
    SELECT Progress.UserID, Questions.[Question Location],Questions.[Correct Answer], Questions.[False Answer 1],
    Questions.[False Answer 2], Questions.[False Answer 3]
    FROM Questions 
    INNER JOIN Progress ON Questions.[QuestionID] = Progress.[QuestionID]
    WHERE (((Progress.UserID)=1) AND ((Progress.Status)<>"Correct"))
) AS subquery;
emily
  • 136
  • 1
  • 2
0

A simple way is to use a subquery:

select count(*)
from (<your query here>) as q;

In your case, you can also change the select to be:

select count(*)

but that would not work for aggregation queries.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Hi there, thanks for your response. what do you mean by "as q"? thanks – Joe Jones Jan 01 '16 at 17:35
  • don't worry, coz it works! Thanks so much, really is gonna help me with my computing coursework. – Joe Jones Jan 01 '16 at 17:37
  • SELECT Count(*) AS Expr1 FROM (SELECT Progress.UserID, Questions.[Question Location], Questions.[Correct Answer], Questions.[False Answer 1], Questions.[False Answer 2], Questions.[False Answer 3] FROM Questions INNER JOIN Progress ON Questions.[QuestionID] = Progress.[QuestionID] WHERE (((Progress.UserID)=1) AND ((Progress.Status)<>"Correct"))) AS q; – Joe Jones Jan 01 '16 at 17:37
0

A completely different approach from the SQL based ones is to count the rows once they are back in your application - you say you are using VB so you may well be using a dataset to hold the results of your query. If so then you only need this bit of code:

dim rowcount as integer = mydataset.mytable.rows.count
peterG
  • 1,651
  • 3
  • 14
  • 23