473,321 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

help with a query

Sam
Hi,

I have one table like :

MyTable {field1, field2, startdate, enddate}

I want to have the count of field1 between startdate and enddate, and
the count of field2 where field2 = 1 between startdate and enddate,
all in the same query.

I know how to get the first part (see below), but i don't know how to
include the count of field2 where field2 = 1 in each row.

select count(field1) as field1
from MyTable
where startdate >= '01-24-2007' and enddate <= '02-25-2007' and field2
= 0
group by field1
Can you help ?
thanks

Feb 27 '07 #1
5 2492
Sam,

Is this what you're looking for?

create table MyTable (Field1 int, Field2 int)
insert MyTable select 1,1
insert MyTable select 1,1
insert MyTable select 2,1
insert MyTable select 2,2

select
Field1
, count(*) as Field1Count
, sum(
case when Field1 = Field2 then 1
else 0
end
) as Field2Count
from MyTable
group by Field1

-- Bill

"Sam" <sa*************@googlemail.comwrote in message
news:11*********************@v33g2000cwv.googlegro ups.com...
Hi,

I have one table like :

MyTable {field1, field2, startdate, enddate}

I want to have the count of field1 between startdate and enddate, and
the count of field2 where field2 = 1 between startdate and enddate,
all in the same query.

I know how to get the first part (see below), but i don't know how to
include the count of field2 where field2 = 1 in each row.

select count(field1) as field1
from MyTable
where startdate >= '01-24-2007' and enddate <= '02-25-2007' and field2
= 0
group by field1
Can you help ?
thanks

Feb 27 '07 #2
Sam wrote:
MyTable {field1, field2, startdate, enddate}

I want to have the count of field1 between startdate and enddate, and
the count of field2 where field2 = 1 between startdate and enddate,
all in the same query.
Based on your sample query, it appears that you want

1) all rows where (startdate to enddate) falls within given limits
2) separate subtotals for each distinct value of field1 where 1) is true

(This is why Erland, Celko, et al. keep ranting about "post your
CREATE TABLE, sample data, and desired output" - because it largely
eliminates the need to make educated guesses such as the above.)

Anyway, this should cover it:

select field1, count(field1), sum(case field2 when 1 then 1 else 0)
from MyTable
where startdate >= '01-24-2007' and enddate <= '02-25-2007'
group by field1
Feb 27 '07 #3
Let me be the bad guy -- I have practice -- and elaborate on Ed's
remark.
> MyTable {field1, field2, startdate, enddate} <<
is useless. Ignoring the bad column and table names, ignoring the
confusion of columns with fields implied by your bad choices, this
could be any of the following:

CREATE TABLE MyTable
(field1 ?? DEFAULT ?? [NOT NULL]
[CHECK (??)],
field2 ?? DEFAULT ?? [NOT NULL]
[CHECK (??)],
start_date DATETIME [NOT NULL],
end_date DATETIME [NOT NULL],
[CHECK (start_date [< | <=] end_date)
[PRIMARY KEY (??)] );

Do you see how many tens of thousands of possible schemas we have to
filter thru because you do not know how to post a spec? If you want
us to do your homework or your job for you, then at least give us a
spec!!

"[I need] Data! Data! Data! I can't make bricks without clay."
-- Sherlock Holmes (fictional detective of author Sir Arthur Conan
Doyle)

Oh, the use of CASE inside aggregate functions is a standard SQL-92
programming trick which you will find useful. Look at the new OLAP
functions which can also be passed to an aggregate -- a trick most SQL
programmers do no tyet know.

Feb 27 '07 #4
--CELKO-- wrote:
Let me be the bad guy -- I have practice -- and elaborate on Ed's
remark.
>> MyTable {field1, field2, startdate, enddate} <<

is useless. Ignoring the bad column and table names, ignoring the
confusion of columns with fields implied by your bad choices,
We still need a URL to answer the perennial "what's the difference
between columns and fields?" question.
this could be any of the following:

CREATE TABLE MyTable
(field1 ?? DEFAULT ?? [NOT NULL]
[CHECK (??)],
field2 ?? DEFAULT ?? [NOT NULL]
[CHECK (??)],
start_date DATETIME [NOT NULL],
end_date DATETIME [NOT NULL],
[CHECK (start_date [< | <=] end_date)
[PRIMARY KEY (??)] );
Most of it is likely irrelevant in this particular case, though of
course it takes some experience to make such a judgment correctly.

* field1's datatype and nullability probably don't matter, as all
we do with it is group by it.

* field2 can be 1, so it's some numeric type; its nullability
probably doesn't matter, as we seek a specific non-null value.

* start_date and end_date's nullability might matter. If start_date
is within the desired range and end_date is null, should that row
be included? Etc.
Feb 28 '07 #5
>>We still need a URL to answer the perennial "what's the difference between columns and fields?" question. <<

That is one of my standard rants, which I have posted for years:

In 25 words or less, a column is active and a field is passive.
Columns have datatypes, defaults and constraints; they can be
materialized or virtual. Fields have meaning given to them by the
host program using thme and must be materialized.

Here is the long version:

Like most new ideas, the hard part of understanding what the
relational model is comes in un-learning what you know about file
systems. As Artemus Ward (William Graham Sumner, 1840-1910) put it,
"It ain't so much the things we don't know that get us into trouble.
It's the things we know that just ain't so."

If you already have a background in data processing with traditional
file systems, the first things to un-learn are:

(0) Databases are not file sets.
(1) Tables are not files.
(2) Rows are not records.
(3) Columns are not fields.

Modern data processing began with punch cards. The influence of the
punch card lingered on long after the invention of magnetic tapes and
disk for data storage. This is why early video display terminals
were 80 columns across. Even today, files which were migrated from
cards to magnetic tape files or disk storage still use 80 column
records.

But the influence was not just on the physical side of data
processing. The methods for handling data from the prior media were
imitated in the new media.

Data processing first consisted of sorting and merging decks of punch
cards (later, sequential magnetic tape files) in a series of distinct
steps. The result of each step feed into the next step in the
process. This leads to temp table and other tricks to mimic that kind
of processing.

Relational databases do not work that way. Each user connects to the
entire database all at once, not to one file at time in a sequence of
steps. The users might not all have the same database access rights
once they are connected, however. Magnetic tapes could not be shared
among users at the same time, but shared data is the point of a
database.

Tables versus Files

A file is closely related to its physical storage media. A table may
or may not be a physical file. DB2 from IBM uses one file per table,
while Sybase puts several entire databases inside one file. A table
is a <i>set<iof rows of the same kind of thing. A set has no
ordering and it makes no sense to ask for the first or last row.

A deck of punch cards is sequential, and so are magnetic tape files.
Therefore, a <i>physical<ifile of ordered sequential records also
became the <i>mental<imodel for data processing and it is still hard
to shake. Anytime you look at data, it is in some physical ordering.

The various access methods for disk storage system came later, but
even these access methods could not shake the mental model.

Another conceptual difference is that a file is usually data that
deals with a whole business process. A file has to have enough data
in itself to support applications for that business process. Files
tend to be "mixed" data which can be described by the name of the
business process, such as "The Payroll file" or something like that.

Tables can be either entities or relationships within a business
process. This means that the data which was held in one file is often
put into several tables. Tables tend to be "pure" data which can be
described by single words. The payroll would now have separate tables
for timecards, employees, projects and so forth.

Tables as Entities

An entity is physical or conceptual "thing" which has meaning be
itself. A person, a sale or a product would be an example. In a
relational database, an entity is defined by its attributes, which are
shown as values in columns in rows in a table.

To remind users that tables are sets of entities, I like to use
collective or plural nouns that describe the function of the entities
within the system for the names of tables. Thus "Employee" is a bad
name because it is singular; "Employees" is a better name because it
is plural; "Personnel" is best because it is collective and does not
summon up a mental picture of individual persons.

If you have tables with exactly the same structure, then they are sets
of the same kind of elements. But you should have only one set for
each kind of data element! Files, on the other hand, were PHYSICALLY
separate units of storage which could be alike -- each tape or disk
file represents a step in the PROCEDURE , such as moving from raw
data, to edited data, and finally to archived data. In SQL, this
should be a status flag in a table.

Tables as Relationships

A relationship is shown in a table by columns which reference one or
more entity tables. Without the entities, the relationship has no
meaning, but the relationship can have attributes of its own. For
example, a show business contract might have an agent, an employer
and a talent. The method of payment is an attribute of the contract
itself, and not of any of the three parties.

Rows versus Records

Rows are not records. A record is defined in the application program
which reads it; a row is defined in the database schema and not by a
program at all. The name of the field in the READ or INPUT statements
of the application; a row is named in the database schema. Likewise,
the PHYSICAL order of the field names in the READ statement is vital
(READ a,b,c is not the same as READ c, a, b; but SELECT a,b,c is the
same data as SELECT c, a, b.

All empty files look alike; they are a directory entry in the
operating system with a name and a length of zero bytes of storage.
Empty tables still have columns, constraints, security privileges and
other structures, even tho they have no rows.

This is in keeping with the set theoretical model, in which the empty
set is a perfectly good set. The difference between SQL's set model
and standard mathematical set theory is that set theory has only one
empty set, but in SQL each table has a different structure, so they
cannot be used in places where non-empty versions of themselves could
not be used.

Another characteristic of rows in a table is that they are all alike
in structure and they are all the "same kind of thing" in the model.
In a file system, records can vary in size, datatypes and structure by
having flags in the data stream that tell the program reading the data
how to interpret it. The most common examples are Pascal's variant
record, C's struct syntax and Cobol's OCCURS clause.

The OCCURS keyword in Cobol and the Variant records in Pascal have a
number which tells the program how many time a record structure is to
be repeated in the current record.

Unions in 'C' are not variant records, but variant mappings for the
same physical memory. For example:

union x {int ival; char j[4];} myStuff;

defines myStuff to be either an integer (which are 4 bytes on most
modern C compilers, but this code is non-portable) or an array of 4
bytes, depending on whether you say myStuff.ival or myStuff.j[0];

But even more than that, files often contained records which were
summaries of subsets of the other records -- so called control break
reports. There is no requirement that the records in a file be
related in any way -- they are literally a stream of binary data whose
meaning is assigned by the program reading them.

Columns versus Fields

A field within a record is defined by the application program that
reads it. A column in a row in a table is defined by the database
schema. The datatypes in a column are always scalar.

The order of the application program variables in the READ or INPUT
statements is important because the values are read into the program
variables in that order. In SQL, columns are referenced only by their
names. Yes, there are shorthands like the SELECT * clause and INSERT
INTO <table namestatements which expand into a list of column names
in the physical order in which the column names appear within their
table declaration, but these are shorthands which resolve to named
lists.

The use of NULLs in SQL is also unique to the language. Fields do not
support a missing data marker as part of the field, record or file
itself. Nor do fields have constraints which can be added to them in
the record, like the DEFAULT and CHECK() clauses in SQL.

Relationships among tables within a database

Files are pretty passive creatures and will take whatever an
application program throws at them without much objection. Files are
also independent of each other simply because they are connected to
one application program at a time and therefore have no idea what
other files looks like.

A database actively seeks to maintain the correctness of all its
data. The methods used are triggers, constraints and declarative
referential integrity.

Declarative referential integrity (DRI) says, in effect, that data in
one table has a particular relationship with data in a second
(possibly the same) table. It is also possible to have the database
change itself via referential actions associated with the DRI.

For example, a business rule might be that we do not sell products
which are not in inventory. This rule would be enforce by a
REFERENCES clause on the Orders table which references the Inventory
table and a referential action of ON DELETE CASCADE

Triggers are a more general way of doing much the same thing as DRI.
A trigger is a block of procedural code which is executed before,
after or instead of an INSERT INTO or UPDATE statement. You can do
anything with a trigger that you can do with DRI and more.

However, there are problems with TRIGGERs. While there is a standard
syntax for them in the SQL-92 standard, most vendors have not
implemented it. What they have is very proprietary syntax instead.
Secondly, a trigger cannot pass information to the optimizer like
DRI. In the example in this section, I know that for every product
number in the Orders table, I have that same product number in the
Inventory table. The optimizer can use that information in setting up
EXISTS() predicates and JOINs in the queries. There is no reasonable
way to parse procedural trigger code to determine this relationship.

The CREATE ASSERTION statement in SQL-92 will allow the database to
enforce conditions on the entire database as a whole. An ASSERTION is
not like a CHECK() clause, but the difference is subtle. A CHECK()
clause is executed when there are rows in the table to which it is
attached. If the table is empty then all CHECK() clauses are
effectively TRUE. Thus, if we wanted to be sure that the Inventory
table is never empty, and we wrote:

CREATE TABLE Inventory
( ...
CONSTRAINT inventory_not_empty
CHECK ((SELECT COUNT(*) FROM Inventory) 0), ... );

it would not work. However, we could write:

CREATE ASSERTION Inventory_not_empty
CHECK ((SELECT COUNT(*) FROM Inventory) 0);

and we would get the desired results. The assertion is checked at the
schema level and not at the table level.
Feb 28 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: James | last post by:
My form and results are on one page. If I use : if ($Company) { $query = "Select Company, Contact From tblworking Where ID = $Company Order By Company ASC"; }
9
by: netpurpose | last post by:
I need to extract data from this table to find the lowest prices of each product as of today. The product will be listed/grouped by the name only, discarding the product code - I use...
9
by: Dom Boyce | last post by:
Hi First up, I am using MS Access 2002. I have a database which records analyst rating changes for a list of companies on a daily basis. Unfortunately, the database has been set up (by my...
8
by: Andrew McNab | last post by:
Hi folks, I have a problem with an MS Access SQL query which is being used in an Access Report, and am wondering if anyone can help. Basically, my query (shown below) gets some records from a...
5
by: Steve Patrick | last post by:
Hi All You guys are my last hope, despite spending money on books and hours reading them I still can not achieve the results I need. I have designed a database in Access 2000 based on 1 table,...
4
by: Alan Lane | last post by:
Hello world: I'm including both code and examples of query output. I appologize if that makes this message longer than it should be. Anyway, I need to change the query below into a pivot table...
6
by: Takeadoe | last post by:
Dear NG, Can someone assist me with writing the little code that is needed to run an update table query each time the database is opened? From what I've been able to glean from this group, the...
3
by: mcmahonb | last post by:
Hey people... I've been searching this forum for a few hours and even though this topic has been went over from many different angles; I cannot seem to figure out how to make things work on my...
4
by: n | last post by:
Hello! Here is a problem I hope you can point me to a solution. It Problem: A teacher needs to know which lesson to teach. A school has a curriculum with 26 lessons, A-Z. For a given class,...
47
by: Jo | last post by:
Hi there, I'm Jo and it's the first time I've posted here. I'm in process of creating a database at work and have come a little unstuck.....I'm a bit of a novice and wondered if anyone could...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.