tags:

views:

68

answers:

3

Hi all,

I need SQL code for a query I need to do in Access. I have a table with multiple fields but I only need 2 fields for the query. 1 is a date field. let's call that one DateField. the other is a field that contains text, let's call lit TextField. I need a query that returns the following:

  1. The COUNT of DateField (i.e. how many there are regardless of what the value is)
  2. The COUNT of TextField WHERE its value = "ThisText"
  3. The COUNT of TextField WHERE its value = "ThatText"
  4. Results GROUP BY Year
  5. the same query again (will be a separate Q) but with results GROUP BY Month

Many thanks in advance for all your wonderful help.

+2  A: 

I believe you can only SELECT a given aggregate function once per per query. That is to say you cannot request the COUNT two different fields in a single query. Here's the reference for the count function in JET SQL. At best you can count the number of non-NULL values of a certain field in a grouped result set under some WHERE clause.

vicatcu
I was getting an error msg something alongthe lines of "aggregate funciton" when I tried to get this to work myself, but thought it might be my rusty SQL. Ultimately I need the results to be in a Report, anyway, the Query is just to feed into the Report. So perhaps I should build 3 Q's, 1 for each COUNT, and then would it be possible to include the results of each Q (Q1, Q2 and Q3) in a single report? I will test out the other 2 repsonses below--give me a few minutes...
rick
Yea, that seems reasonable to me. In that case, your queries would look like this: ` SELECT COUNT(DateField) FROM table GROUP BY whatever; SELECT COUNT(TextField) FROM table WHERE TextField = 'ThisText' GROUP BY whatever; SELECT COUNT(TextField) FROM table WHERE TextField = 'ThatText' GROUP BY whatever;
vicatcu
If @Tor's answer works that's a cool technique. Do let us know!
vicatcu
OK, thank you very much.
rick
A: 

How about:

SELECT 
   Year
   ,COUNT(DISTINCT DateField) AS NumDateFields
   ,COUNT(CASE WHEN TextField = 'ThisText' THEN 1 END) AS ThisTextCount
   ,COUNT(CASE WHEN TextField = 'ThatText' THEN 1 END) AS ThisTextCount
GROUP BY Year;

Or... GROUP BY Month

Rob Farley
A: 
SELECT YEAR/MONTH(DateField), COUNT(DateField), 
       SUM(IIF(TextField='ThisText', 1, 0)),
       SUM(IIF(TextField='ThatText', 1, 0))
FROM MyTable
GROUP BY YEAR/MONTH(DateField)
Tor Valamo
This appears to work! I think i see what you are doing--instead of using the built-in COUNT fxn, you are custom forcing it to sum the instances of a particular value, assigning a match = 1 and non-match = 0, then sum is for all intents and purposes the same as the total # of that type. I need to double-check the accuracy, hold on...
rick
Yes, it works. thanks!
rick
Yes, IIF is basically a ternary operator, like "true ? yes : no".
Tor Valamo