How can I get this query to print a record that only exists in one table? - sql

I am trying to create a query that will accept a date from the user and display information from two tables based on this date. This works for all of my tests except my last test. My last test, I enter a date that should return a record that only exists in the expmast table and does not exist in the expbycc table. When I enter the date to try and get this record to be returned, it tells me no records have been found. I know this is because in my where, i have an AND that checks if M.ExpNum = C.ExpNUm which isn;t true for this record because it only exists in one table. I can not figure out how to get this query to work. Any help/advice is greatly appreciated. Below is my script, followed by the table structures used for this query, thank you.
Script:
ACCEPT Date PROMPT 'Enter a date:';
SELECT M.ExpNum, EDate, IsCash, StoreCode, CashAmt, CType, CCNum, Amt
FROM ExpMast M, ExpByCc C
WHERE EDate = to_date('&Date','mm-dd-yy')
AND M.ExpNum = C.ExpNum;
Tables:
CREATE TABLE EXPMAST
(ExpNum NUMBER(2,0) NOT NULL PRIMARY KEY,
EDate DATE,
IsCash VARCHAR2(1),
StoreCode VARCHAR2(4),
CONSTRAINT fk_STORE_EXPMAST FOREIGN KEY (StoreCode)
REFERENCES STORE (Code)
);
CREATE TABLE ExpByCC
(ExpNum NUMBER(2,0) NOT NULL,
CType VARCHAR2(1) NOT NULL,
CCNum VARCHAR2(16) NOT NULL,
Amt DECIMAL(5,2),
CONSTRAINT fk_CRCARD_ExpByCC FOREIGN KEY (CType, CCNum)
REFERENCES CRCARD (CType, CCNum),
CONSTRAINT fk_EXPMAST_ExpByCC FOREIGN KEY (ExpNum)
REFERENCES EXPMAST (ExpNum),
CONSTRAINT pk_ExpByCC PRIMARY KEY (ExpNum, CType, CCNum)
);

You need a left outer join. And you can't express an outer join using your implicit join syntax. You want to use explicit joins in the from clause.
A simple rule: NEVER use commas in the from clause.
Now, it is easy:
SELECT M.ExpNum, EDate, IsCash, StoreCode, CashAmt, CType, CCNum, Amt
FROM ExpMast M LEFT OUTER JOIN
ExpByCc C
ON M.ExpNum = C.ExpNum AND
WHERE M.EDate = to_date('&Date','mm-dd-yy') AND
C.ExpNum IS NULL;

Related

How to update a column in a table A using the value from another table B wherein the relationship between tables A & B is 1:N by using max() function

I have two tables namely loan_details and loan_his_mapping with 1:N relationship. I need to set the hhf_request_id of loan_details table by the value which is present in the loan_his_mapping table for each loan.
Since the relationship is 1:N , I want to consider the record for each loan from loan_his_mapping table with two conditions mentioned below. The table definitions are as follows:
CREATE TABLE public.loan_details
(
loan_number bigint NOT NULL,
hhf_lob integer,
hhf_request_id integer,
status character varying(100),
CONSTRAINT loan_details_pkey PRIMARY KEY (loan_number)
);
CREATE TABLE public.loan_his_mapping
(
loan_number bigint NOT NULL,
spoc_id integer NOT NULL,
assigned_datetime timestamp without time zone,
loan_spoc_map_id bigint NOT NULL,
line_of_business_id integer,
request_id bigint,
CONSTRAINT loan_spoc_his_map_id PRIMARY KEY (loan_spoc_map_id),
CONSTRAINT fk_loan_spoc_loan_number_his FOREIGN KEY (loan_number)
REFERENCES public.loan_details (loan_number) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION );
The joining conditions while updating are:
The Records of loan_details with hhf_lob = 4 and status='Release'
I should consider that record for updating value among 'N' number of records from loan_his_mapping table with value max(loan_spoc_map_id) for each loan.
The query I have right now
update lsa_loan_details ldet
set hhf_request_id = history.request_id
from loan_his_mapping history
where ldet.loan_number = history.loan_number and ldet.status='Release' and ldet.hhf_lob=4 and
history.line_of_business_id=4 ;
I want to know how to use that record for each loan from loan_his_mapping with max(loan_spoc_map_id) to update column of loan_details table. Please Assist!
You need a sub-query to fetch the row corresponding to the highest loan_spoc_map_id
Something along the lines:
update loan_details ldet
set hhf_request_id = history.request_id
from (
select distinct on (loan_spoc_map_id) loan_number, request_id
from loan_his_mapping lhm
where lhm.line_of_business_id = 4
order by loan_spoc_map_id desc
) as history
where ldet.loan_number = history.loan_number
and ldet.status = 'Release'
and ldet.hhf_lob = 4;

I have a problem with the grouping for this query

I have a problem grouping a 4 join table.
Due to new government regulations, every private service vehicle must be periodically serviced and have proper training, RideWiki is required to report to the government with proof that each driver has the required documents to be eligible to be a private service driver.
List the drivers that have serviced their car within the last two months (After 16/4/2019)
and have had done their basic driver training.
Carservice>>Driver<
select Dname
from driver,carservice,dsession,training;
where driver.dnric = carservice.dnric
and driver.dnric = dsession.dnric
and dsession.tid = training.tid
where sysdate-servicedate < 60
group by dnric,tid,dname;
CREATE TABLE DRIVER
(
DNRIC CHAR(12) PRIMARY KEY,
DGrade CHAR(1),
DLicense NUMBER(8),
DStart DATE,
DIPlan CHAR(1),
DName VARCHAR(20),
DDOB DATE,
DGENDER CHAR(1),
DMOBILE NUMBER(11)
);
CREATE TABLE CARSERVICE
(
DCarID NUMBER(6) PRIMARY KEY,
CarType VARCHAR(20),
ServRem VARCHAR(250),
DNRIC CHAR(12),
CarServ CHAR(1),
FOREIGN KEY (DNRIC) references DRIVER(DNRIC)
);
CREATE TABLE DSESSION
(
SID NUMBER(7) PRIMARY KEY,
SDate DATE,
DNRIC CHAR(12),
TID NUMBER(6),
FOREIGN KEY (DNRIC) references DRIVER(DNRIC),
FOREIGN KEY (TID) references TRAINING(TID)
);
CREATE TABLE TRAINING
(
TID NUMBER(6) PRIMARY KEY,
TrainingPrg VARCHAR(50),
PrgSession VARCHAR2(10)
);
You referenced a wrong column name in servicedate where you mentioned as sdate while creating a table.
SELECT DISTINCT Dname
FROM driver d
INNER JOIN carservice car ON d.dnric = car.dnric
INNER JOIN dsession dses ON d.dnric = dses.dnric
INNER JOIN training train ON dses.tid = train.tid
WHERE sysdate-dses.sdate < 60
Few good practices to keep in mind:
Using table aliases d,car,dses,train of your choice to access data.
Use ANSI syntax (JOIN statements) rather than your alternate syntax for better readability of code.
Don't miss any syntax errors to hide your way.
Also, you should mention constraint variable properly if using ORACLE / SQL Server / MS Access
CONSTRAINT FK_DNRIC FOREIGN KEY (DNRIC) references DRIVER(DNRIC),
Hope this helps.
You have a wrong semicolon at the end of the from row.
Also, you have not used an aggregation function so you shoud not use group by.
Use distinct if you need to not repeat values.
select distinct Dname
from driver
INNER JOIN carservice ON driver.dnric = carservice.dnric
INNER JOIN dsession ON driver.dnric = dsession.dnric
INNER JOIN training ON dsession.tid = training.tid
Where sysdate-servicedate < 60
You should use the explict join syntax and avoid the old (from 1992) implicit join syntax based on the where clause.
Thanks alot guys!! I had alot of help just with querying with INNER JOIN.

SQL Join - Query error

So I would like to display the most experience player, at first I was going to display all players and experiencepoints then try and only display the max. so heres the code for both tables and the query itself
CREATE TABLE Player
(
Player_ID INTEGER CONSTRAINT pk_player PRIMARY KEY,
Pname VARCHAR(60),
DOB VARCHAR(10),
Heightcm NUMBER(10),
Weightkg NUMBER(10),
Position VARCHAR(20),
Team_ID INTEGER CONSTRAINT fk_player REFERENCES Team(Team_ID)
)
CREATE TABLE PlayerCareer_Performance
(
Player_Performance_ID INTEGER CONSTRAINT pk_PP PRIMARY KEY,
Player_ID INTEGER,
total_points NUMBER(10),
total_fouls NUMBER(10),
ExperiencePoints NUMBER(10),
CONSTRAINT fk_Pp FOREIGN KEY (Player_ID) REFERENCES Player(Player_ID)
)
Thats the table code, below is the query:
SELECT PLAYER.PLAYER_ID,PLAYER.PNAME,PLAYERCAREER_PERFORMANCE.EXPERIENCEPOINTS
FROM PLAYER
JOIN PLAYERCAREER_PERFOMANCE
ON PLAYERPERFROMANCE.PLAYER_ID = PLAYER.PLAYER_ID;
Player is underlined on yellow and it says "Is disconnected from the rest of join graph"
Any ideas, anyone? I cant see a fix for it :(
At first sight, you are joining the table PLAYERCAREER_PERFORMANCE but joining on a field of table called PLAYERPERFROMANCE (sic). Is that a typo?
This:
SELECT Player.Player_ID, Player.Pname, PlayerCareer_Performance.ExperiencePoints
FROM Player
JOIN PlayerCareer_Performance
ON PlayerCareer_Performance.Player_ID = Player.Player_ID
Seems to work fine (just corrected the typo): check it at sqlfiddle.
As a general suggestion, keep your code consistent... you are using different column formats (e.g.: ExperiencePoints vs total_points), and are putting all SQL query code in caps, which just makes it difficult to read and find typos
Use an inner join (updated to reflect popular demand):
select p.player_id, p.pname, pcp.experiencepoiuts
from Player p
inner join PlayerCareer_Performance pcp on pcp.player_id = p.player_id

Can't serialize transient record type postgres

I am trying to make my calculation dynamic based on certain criteria as below, but when I try to send the fields dynamically in to my calculation logic, it fails with the error " Can't serialize transient record type":
Create table statement :
create table calculation_t(
Id serial,
product_id integer not null,
metric_id integer not null,
start_date date,
end_date date,
calculation_logic varchar(50),
insert_timestamp timestamp default current_timestamp,
CONSTRAINT calculation_pk PRIMARY KEY(Id),
CONSTRAINT calculation_pid_fk FOREIGN KEY(product_id) REFERENCES Product_T(Product_id),
CONSTRAINT calc_mid_fk FOREIGN KEY(metric_id) REFERENCES metric_T(metric_id)
);
Insert statement :
insert into calculation_t(product_id,metric_id,calculation_logic)
select a.product_id,b.metric_id,
(case when b.metric_id=2 then
('$1-$2') else
'$1/$2' end) calc
from product_t a,metric_t b
Select statement which throws the mentioned error :
select *,(1,2,calculation_logic) from calculation_t
Note : I am using Greenplum database.
Try to remove parenthesis form your query:
select *,1,2,calculation_logic from calculation_t
It worked for me.
Thanx,

Microsoft Access - Enter Parameter Value why?

I am encountering a problem for my database.
And tried to do the query for how many transactions have movie "Harry_Potter"?
so I used SQL query:
SELECT
COUNT(td.movie) AS number_of_occurrence,
td.transaction_number
FROM
TransactionDetails td,
MovieDetails md
WHERE
md.movie = Harry_Potter
But it asks for Harry_Potter enter parameter value why?
The relevant SQL statements are
CREATE TABLE TransactionDetails
(
transaction_number INTEGER PRIMARY KEY,
movie VARCHAR(30) NOT NULL,
date_of_transaction DATE NOT NULL,
member_number INTEGER NOT NULL
)
CREATE TABLE MovieDetails
(
movie VARCHAR(30) PRIMARY KEY,
movie_type VARCHAR(3) NOT NULL,
movie_genre VARCHAR(10) NOT NULL
)
ALTER TABLE TransactionDetails
ADD CONSTRAINT member_number_fk FOREIGN KEY (member_number) REFERENCES LimelightMemberDetails(member_number);
ALTER TABLE TransactionDetails
ADD CONSTRAINT transaction_number_drink_fk FOREIGN KEY (transaction_number) REFERENCES DrinkTransactionDetails(transaction_number);
ALTER TABLE TransactionDetails
ADD CONSTRAINT transaction_number_food_fk FOREIGN KEY (transaction_number) REFERENCES FoodTransactionDetails(transaction_number);
ALTER TABLE TransactionDetails
ADD CONSTRAINT movie_fk FOREIGN KEY (movie) REFERENCES MovieDetails (movie);
Thank you for your help! If there is anything wrong with my database design please let me know! thank you!
Change the query to something like
SELECT
COUNT(td.movie) AS number_of_occurrence,
td.transaction_number
FROM
TransactionDetails td,
MovieDetails md
WHERE
md.movie = "Harry_Potter"
Seeing as movie is a string, you need quotes around the value you are looking for.
If I am not mistaken MS Access takes " and SQL SERVER takes '
try this
md.movie = "Harry_Potter"
I guess, you are simply missing the quotation marks around the string you are comparing.