r/SQL•
MimikOctopus

Troubles with count

I'm trying to count the number of videos each member has that are not returned. I have mostly what I need with the following query:

SELECT      COUNT(*)
FROM        video_rental_record x
INNER JOIN  video_copy y
ON          x.video_copy_id = y.video_copy_id
WHERE       member_id = 2004
AND         status = UPPER('r');

This statement gets me what I want for everything but the ID 2004, the value should be 0. I'm writing a PL/SQL program, so the member_id comes from a input, but I've hardcoded it here.

Here is the video_copy table data and here is the video_rental_record table. I basically want to exclude record 12 from the second table without hardcoding, but I'm lost. I tried checkout_date > return_date, but then I lose the null values. I've been looking at this too long and think I've overlooked something simple.

EDIT: Tables are as follows:

CREATE TABLE video_copy 
( VIDEO_COPY_ID       	NUMBER 	PRIMARY KEY,
  VIDEO_ID      		NUMBER 	NOT NULL REFERENCES VIDEO (VIDEO_ID),
  STATUS        		CHAR NOT NULL CONSTRAINT ck_item 
						CHECK (STATUS in ('A', 'R', 'D')));
/

CREATE TABLE video_rental_record
( MEMBER_ID    	NUMBER 	REFERENCES MEMBER (MEMBER_ID),
  VIDEO_COPY_ID  	NUMBER 	REFERENCES VIDEO_COPY (VIDEO_COPY_ID),
  CHECKOUT_DATE   DATE NOT NULL,
  DUE_DATE  	DATE NOT NULL,
  RETURN_DATE  	DATE,
  CONSTRAINT 	pk_rental PRIMARY KEY 
				(MEMBER_ID, VIDEO_COPY_ID, CHECKOUT_DATE));

EDIT 2: I figured out how to get it to work by doing a count where the status = 'r' and the checkout_date > return_date, and then a second count where the status = 'r' and the return_date IS NULL and then adding the variables together. It works, I just hoped I could do it in a less complex way.

Posted May 29, 2016, 7:35 PM UTC · edited

45
Loading comments…