I have an SQL table that looks like this:
CREATE TABLE diet_watch (
entry_date date NOT NULL,
user_id int default 1,
weight double precision NOT NULL
);
INSERT INTO diet_watch VALUES ('2001-01-01', 1, 128.2);
INSERT INTO diet_watch VALUES ('2001-01-02', 1, 121.2);
INSERT INTO diet_watch VALUES ('2001-01-03', 1, 100.6);
INSERT INTO diet_watch VALUES ('2001-01-04', 1, 303.7);
INSERT INTO diet_watch VALUES ('2001-01-05', 1, 121.0);
INSERT INTO diet_watch VALUES ('2001-01-01', 2, 121.0);
INSERT INTO diet_watch VALUES ('2001-01-06', 2, 128.0);
INSERT INTO diet_watch VALUES ('2001-01-07', 2, 138.0);
INSERT INTO diet_watch VALUES ('2001-01-01', 3, 128.2);
INSERT INTO diet_watch VALUES ('2001-01-02', 3, 125.5);
INSERT INTO diet_watch VALUES ('2001-01-03', 3, 112.8);
INSERT INTO diet_watch VALUES ('2001-01-06', 3, 111.2);
I further have this table:
CREATE TABLE summing_period (
user_id INT NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL);
insert into summing_period VALUES (1, '2001-01-01', '2001-01-03');
insert into summing_period VALUES (2, '2001-01-02', '2001-01-06');
insert into summing_period VALUES (3, '2001-01-03', '2001-01-06');
I want to write a query that returns DISTINCT ROWS with the following columns:
- the user_id
- the sum of the weights in table
diet_watchbetween the specified dates in table summing_period (for the user_id)
So the result of the query based on the data in table summing period should be:
1,350.0
2,128.0
3,224.0
Unfortunately, this time, I have reached the limit of my SQLfu – and I no idea how to even get started in writing the SQL. Ideally, the solution should be ANSI SQL (i.e. db agnostic). however, since I am developing to a PostgreSQL 8.4 backend, if the solution is db centric, it must at least run on PG.
What this query does is join each
diet_watchrow to the row insumming_periodthat matches itsuser_idand whose date falls in thesumming_period‘s range.The
SELECTthen asks for theSUMof the weights for each differentuser_id(as a result of theGROUP BY user_id).