SQL double primary key, many-to-many relationship - sql

I'd like to connect 3 tables. In one of them I must use a compound primary key. I know, how to deal with single. I have the following tables to connect:
CREATE TABLE Med_list
(
ID_med_list INT IDENTITY(200001,1) ,
No_med_list INT,
ID_med INT REFERENCES Med(ID_med),
PRIMARY KEY(ID_med_list, No_med_list)
)
CREATE TABLE Med
(
ID_med INT IDENTITY(3001,1) PRIMARY KEY ,
Name VARCHAR(20)
)
CREATE TABLE Visit
(
ID_Visit INT IDENTITY(600001,1) PRIMARY KEY,
ID_patient INT REFERENCES Patients(ID_patient),
Visit_date Datetime,
ID_med_duty INT,
No_med_list INT
)
I would like to every patient could have more than one medicine during one visit. I don't know how to connect table Visit and Med_list the way acceptable to SQL Server.
Thank you in advance for every hint or help:)

You need a many to many relation, if Med_list is supposed to be this relation (medicine to visits) then you are only missing one foreign key that points to the visit so the tables relation looks like this
Patient. <--- Visit. <--- Med_list. ---> Meds
The tables like this:
CREATE TABLE Med_list
(
ID_med_list INT IDENTITY(200001,1) ,
No_med_list INT,
ID_med INT REFERENCES Med(ID_med),
ID_Visit INT REFERENCES Visit(ID_Visit)
PRIMARY KEY(ID_med_list, No_med_list)
)
CREATE TABLE Med
(
ID_med INT IDENTITY(3001,1) PRIMARY KEY ,
Name VARCHAR(20)
)
CREATE TABLE Visit
(
ID_Visit INT IDENTITY(600001,1) PRIMARY KEY,
ID_patient INT REFERENCES Patients(ID_patient),
Visit_date Datetime,
ID_med_duty INT,
No_med_list INT
)
And your query can look like this
Select * From patients p
Join Visit v on v.ID_Patient = p.ID_Patient
Join Med_list ml on ml.ID_Visit = v.ID_Visit
Join Med m on m.ID_med = ml.ID_med

You could try this
I am also new in many-to-many relationship query.
SQLFiddle Example
SELECT
P.name,
M.Name
FROM
med_list ML
LEFT JOIN med M ON m.ID_med=ML.ID_med
LEFT JOIN visit V ON V.ID_Visit=ML.ID_Visit
LEFT JOIN patients P ON P.ID_patient=V.ID_patient

Related

How to find the champion with the highest number of selections in match in SQLlite

I'm trying to do this query : find the champion with the highest number of selections in match for each champion found display their name as well as the number of times they ha\ve been selected in match .
Here are the tables:
CREATE TABLE champions
(
id_champion INT PRIMARY KEY NOT NULL,
name VARCHAR(20),
title VARCHAR(20),
attack INT,
defense INT,
magic INT,
difficulty INT
);
CREATE TABLE players
(
id_player INT PRIMARY KEY NOT NULL,
name VARCHAR(20),
country VARCHAR(20)
);
CREATE TABLE matchs
(
id_match INT,
player INT,
champion INT,
number INT,
gold INT,
team INT,
position VARCHAR(10),
PRIMARY KEY (id_match, player),
FOREIGN KEY(id_match) REFERENCES matchsmeta(id_match) ON DELETE SET NULL,
FOREIGN KEY(player) REFERENCES players(id_player) ON DELETE SET NULL,
FOREIGN KEY(champion) REFERENCES champions(id_champion) ON DELETE SET NULL
);
CREATE TABLE matchsmeta
(
id_match INT PRIMARY KEY NOT NULL,
time INT,
victory INT,
date DATE,
game_mode VARCHAR(10)
);
First aggregate in the table matchs to get the number of times each champion was picked and use MAX() window function to get the max of these counts:
SELECT champion,
COUNT(*) counter,
MAX(COUNT(*)) OVER () max_counter
FROM matchs
GROUP BY champion
Then join the above query to the table champions:
SELECT c.name, m.counter
FROM champions c
INNER JOIN (
SELECT champion,
COUNT(*) counter,
MAX(COUNT(*)) OVER () max_counter
FROM matchs
GROUP BY champion
) m ON m.champion = c.id_champion
WHERE m.counter = m.max_counter;
You have to make the count of times a champion appears in matchs table.
Then you can join the champions table to get the name.
SELECT
m.champion,
c.name,
SUM(1) as num_times_picked
FROM matchs m
LEFT JOIN champions c on (m.champion = c.id_champion)
GROUP BY m.champion
ORDER BY 3 DESC

Joining multiple tables + HAVING clause

I have 4 tables :
create table Hotel (
numHotel int primary key,
nomHotel varchar(30),
ville varchar(30),
etoiles tinyint
);
create table Chambre (
numChambre int identity primary key,
numHotel int foreign key references Hotel(numHotel),
etage tinyint,
prixnuit smallmoney not null check (prixnuit>=100)
);
create table Client (
cinClient varchar(10) primary key,
nom varchar(30),
prenom varchar(30),
adresse varchar(255) default 'non renseignée',
telephone varchar(10) check (telephone like '0%' and len(telephone)=10)
);
create table reservation (
numReservation int identity primary key,
numChambre int foreign key references Chambre(numChambre),
numCl varchar(10) foreign key references Client(cinClient),
dateArrivee date,
dateDepart date,
constraint ck_dates check ((Datediff(day,dateArrivee,dateDepart)>0))
);
Column names are French, but I think they're understandable.
So the question is : I need to select the names of Hotels (nomHotel) having achieved a total price higher than a certain price (e.g. 10000)
This is what I did on paper :
select nomHotel from Hotel h join Chambre ch on h.numHotel=ch.numChambre join reservation r on ch.numChambre=r.numChambre
group by nomHotel
having COUNT(r.numChambre)*ch.prixnuit>10000
And (of course) I got it wrong.
Any Help is appreciated, Thanks.
translations : "prixnuit" is the room's (chambre) price per night.
The total revenue (I think) is based on the number of reservations.
I'm thinking you need to calculate the number of nights per reservation, no?
So, maybe:
select nomHotel,
sum(Datediff(day,r.dateArrivee,r.dateDepart)*ch.prixnuit)
from Hotel h join Chambre ch on h.numHotel=ch.numChambre join reservation r
on ch.numChambre=r.numChambre
group by nomHotel
having sum(Datediff(day,r.dateArrivee,r.dateDepart)*ch.prixnuit)>10000
select nomHotel, sum(Datediff(day,dateArrivee,dateDepart) * prixnuit)
from Hotel h join Chambre ch on h.numHotel=ch.numHotel
join reservation r on ch.numChambre=r.numChambre
group by nomHotel
having sum(Datediff(day,dateArrivee,dateDepart) * prixnuit)>1000

How to join in sql with multiple tables (need) join multiple references?

Some table only have identity columns but this is because this is a example only.
create table producto(
idproducto int identity primary key
)
create table inventario(
idInventario id int identity primary key,
idproducto int,
foreign key (idproducto) references producto(idproducto)
)
create table sucursal(
idSucursal id int identity primary key
)
create table inventariosucursal(
idinventariosucursal id int primary key,
idsucursal int,
idinventario int,
foreign key (idsucursal) references sucursal (idsucursal),
foreign key (idinventario) references inventario (idinventario),
)
create table mejoresventasxsucursal
(
mejoresventasxsucursal id int primary key,
idsucursal int,
idproducto int,
foreign key (idsucursal) references sucursal(idsucursal),
foreign key (idproducto) references producto (idproducto)
)
What do I need?
select the stocking ( inventario table ) by every branch office (sucursal table) but only most selled products (mejoresventasxsucursal table).
the problem is mejoresventasxsucursal table does "join" with 2 tables product and sucursal but after i have other table with does "join" with same 2 tables product and sucursal.
select s.id,i.id,p.id,
from producto p
join inventario i on p.idproducto = i.idproducto
join inventariosucursal i_s on i_s.idinventario = i.idinventario
join sucursal s on i_s on i_s.idsucursal = s.idsucursal
join producto p on i.producto = p.idproducto
join mejoresventasxsucursal mv on mv.idsucursal = s.idsucursal
Here is the problem. I need join mejoresventasxsucursal with producto. I know I could do something as join producto p2 but I would like to know what is the best way for join with producto. I know other solution is in where condition doing where p.idproducto=mv.idprocucto

Sql one to many relationship

In my application I have the following Clients, Products. I want for each Client to have certain Products( one to many relationship) my code :
Tables Creation :
Create Table Client
(
IDC int identity(1,1) not null primary key,
NumeC nvarchar(50),
CIF nvarchar(50) unique
)
Create Table Produs
(
IDP int identity(1,1) not null,
NumeP nvarchar(50),
Cantitate int,
IDC int
)
this the Foreign Key :
Alter table Produs add constraint FK_Client_Produs_IDC
Foreign key (IDC) references Client(IDC)
Select statement Query to join Clients and foreach client to show Products :
Select NumeC,CIF from Client
Inner Join Produs
ON Client.IDC = Produs.IDC
I don't know what am I doing wrong, I just want to show Products for each client. It does not give me that. It just repeats the name of the client, now showing me The products for each client
In your SELECT you don't ever include anything from the Produs table, so why would it show it to you.
Select NumeC,CIF,NumeP
from Client
Inner Join Produs
ON Client.IDC = Produs.IDC

How to select IDs from a table if two conditions in other tables match

I am developing a user feedback system using ASP.NET and C#. I have multiple tables and am trying to populate dropdown lists so that the feedback can be filtered.
My tables:
CREATE TABLE tblModules
(
Module_ID nvarchar(10) PRIMARY KEY,
Module_Title nvarchar(MAX) NOT NULL
);
CREATE TABLE tblQuestions
(
Q_ID int PRIMARY KEY IDENTITY(1,1),
Question_Text varchar(1000) NOT NULL
);
CREATE TABLE tblFeedback
(
Submission_ID int PRIMARY KEY IDENTITY(1,1),
Username varchar(100) NOT NULL,
Domain varchar(50) NOT NULL,
DateTime_Submitted datetime NOT NULL
Module_ID nvarchar(10)
FOREIGN KEY (Module_ID) REFERENCES tblModules (Module_ID);
);
CREATE TABLE tblAnswers
(
Q_ID int NOT NULL,
Submission_ID int NOT NULL,
Answer_Text varchar(max),
FOREIGN KEY (Q_ID) REFERENCES tblQuestions(Q_ID),
FOREIGN KEY (Submission_ID) REFERENCES tblFeedback(Submission_ID)
);
I have two dropdown lists. First one is populated with all modules from a table. The second needs to be populated with Questions from tblQuestions but only if any answers to it exist (therefore if the Question ID 'Q_ID' exists in tblAnswers).
I can get the selectedModuleID from the first dropdown list. I have a List of all Questions referenced by Q_ID in tblAnswers. How do I crossreference this list with the module ID?
Each feedback submission gets a Submission ID and Module ID.
You want:
questions that have answers
questions that have a module parent (via tblfeedback)
So, my guess at what you want:
SELECT
*
FROM
tblQuestions Q
WHERE
EXISTS (SELECT *
FROM
tblAnswers A
JOIN
tblFeedback F ON A.Submission_ID = F.Submission_ID
WHERE
Q.Q_ID = A.Q_ID AND F.Module_ID = #moduleID)
This should do the trick...
SELECT Q_ID, Question_Text tblQuestions a
WHERE EXISTS (SELECT NULL FROM tblAnswers a WHERE a.Q_ID = q.Q_ID)