How to store date and compare it in sql server? - sql

basically, i need to make database for plants and their harvest dates.
For example, table with all the plants.
CREATE TABLE plant
(
plant_name NVARCHAR(20) NOT NULL
PRIMARY KEY ,
best_to_harvest_day INT NOT NULL ,
best_to_harvest_month NVARCHAR(15)
)
Example for plant entry: Rose 16 December
And another table called harvests
Where are multiple harvested plants and dates when they were harvested.
CREATE TABLE harvests
(
plant_name nvarchar(20) NOT NULL FOREIGN KEY REFERENCES plant(plant_name),
amount int NOT NULL,
havested_day int NOT NULL,
harvested_month nvarchar(15),
harvested year int NOT NULL
)
And this method does work, because i can make a sql query to compare which plants are harvested at their best time etc.
But isnt there a tidy way?
something like this: (using the date)
CREATE TABLE plant
(
plant_name NVARCHAR(20) NOT NULL
PRIMARY KEY ,
best_to_harvest DATE --But here should only be day and month, not year.
)
CREATE TABLE harvests
(
plant_name NVARCHAR(20) NOT NULL
FOREIGN KEY REFERENCES plant ( plant_name ) ,
amount INT NOT NULL ,
harvested DATE --But here i need full date year,day,month
)
Bottom line is that i need to compare them.
Okay, i think i can use EXTRACT(unit FROM date)
and then compare them but the question still stands, how to make plant table date not to consist of year?

First, store the date parts as numbers and check their values. This isn't perfect, but probably good enough:
CREATE TABLE plant (
plant_id int not null PRIMARY KEY,
plant_name nvarchar(20) NOT NULL UNIQUE,
best_to_harvest_day int NOT NULL,
best_to_harvest_month int not NULL,
check (best_to_harvest_day between 1 and 31),
check (best_to_harvest_month between 1 and 12)
);
Note the inclusion of an integer identity primary key. This is recommended, because integers are more efficient for foreign key references.
Then use date for the harvest:
CREATE TABLE harvests (
harvest_id int not null primary key,
plant_id int NOT NULL FOREIGN KEY REFERENCES plant(plant_id),
amount int NOT NULL,
harvested date --But here i need full date year,day,month
);
And you can do:
select h.*,
(case when p.best_to_harvest_day = day(h.harvest_day) and
p.best_to_harvest_month = month(h.harvest_month)
then 'Y' else 'N'
end)
from harvest h join
plant p
on h.plant_id = p.plant_id;

Related

Is there a way to relationship between two table which table one has 3 unique keys and table two has 2 unique keys in SQL Server?

I want to create relation between two tables, here's my table structure
Table1:
ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
SubDivision VARCHAR(10) UNIQUE
Table2:
ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
ReportNo VARCHAR(10) UNIQUE
Table1:
ID |CountryCode |Division |SubDivision
-------+------------------+--------------+-----------
1 |IDN |A |A-1
2 |IDN |B |B-1
3 |IDN |B |B-2
Table2
ID |CountryCode |Division |ReportNo
-------+------------------+--------------+-----------
1 |IDN |A |Re001
2 |IDN |A |Re002
3 |IDN |B |Re003
I want to create a relationship between those two tables which table2 (CountryCode, Division) refers to table1 (CountryCode, Division).
So when I want to delete in table1 with CountryCode = IDN and Division = A, SQL will prompt error when table2 contains CountryCode = IDN and Division = A.
I had tried to create a relationship between those two tables, but SQL Server always throws this error:
The column in table 'table1' do not match an existing primary key or unique constraint
Can anyone guide me how can I create a relationship between those two tables?
Thanks in advance
You can't do it this way. SQL Server requires a unique constraint (or primary key constraint) on the target of a foreign key - and you have duplicates in the source table.
For this to work, you would need to have a separate table that references all possible (CountryCode, Division) combinations. Actually, your whole schema should be normalized into something like:
-- "top" table that stores the countries
create table countries (
country_id int primary key
name varchar(100)
);
-- the table that stores the divisions
create table divisions (
division_id int primary key,
country_id int references countries(country_id),
name varchar(100)
);
-- the table that stores the subdivisions
-- this corresponds to "table1" in your question
create table subdivisions (
subdivision_id int primary key,
division_id int references divisions(division_id),
name varchar(100)
);
-- the table that stores the reports
-- this corresponds to "table2" in your question
create table reports (
report_id int primary key,
division_id references divisions(division_id),
name varchar(100)
);
You can make the primary keys automatic by using identity columns (which is the SQL Server equivalent for MySQL's AUTO_INCREMENT).
As an example, here is how you would generate the current output that you are showing for the subdivisions:
select
sd.id,
c.name country,
d.name division,
sd.name subdivision
from subdivisions sd
inner join divisions d on d.division_id = sd.division_id
inner join countries c on c.country_id = d.country_id
As GMB has answered you cannot do it in this way because of the duplicates. GMB's answer is the best way to solving your problem. If for some reason you cannot follow his advice then maybe my answer would help.
You could use a composite primary key on the columns CountryCode, Division, SubDivision. Then add subdivision to Table2. And then reference this primary key in the foreignkey restraint. (notice that my example throws an error on purpose to show that the value cannot be deleted)
DROP TABLE IF EXISTS Table2;
DROP TABLE IF EXISTS Table1;
CREATE TABLE Table1
(ID INT IDENTITY(1,1)
, CountryCode CHAR(3)
, Division VARCHAR(4)
, SubDivision VARCHAR(10)
, CONSTRAINT PK_Table1 PRIMARY KEY(CountryCode, Division, SubDivision)
)
INSERT INTO Table1(CountryCode, Division, SubDivision)
VALUES ('IDN', 'A', 'A-1')
, ('IDN', 'B', 'B-1')
, ('IDN', 'B', 'B-2');
CREATE TABLE Table2
(ID INT IDENTITY(1,1) PRIMARY KEY
, CountryCode CHAR(3)
, Division VARCHAR(4)
, SubDivision VARCHAR(10)
, ReportNo VARCHAR(10)
, CONSTRAINT FK_CountryDivision FOREIGN KEY(CountryCode, Division, SubDivision) REFERENCES Table1(CountryCode, Division, SubDivision)
);
INSERT INTO Table2(CountryCode, Division, SubDivision, ReportNo)
VALUES ('IDN', 'A', 'A-1', 'Re001')
, ('IDN', 'B', 'B-1', 'Re002')
, ('IDN', 'B', 'B-2', 'Re003');
DELETE FROM Table1
WHERE Division = 'A';
Of course this change could add a whole set of new problems for instance when a report is for the whole division what should the subdivision value then be.
ps. i had to change up the example tables a bit because the values did not match, ie string values into an int column.
SQL fiddle
thank you for the all greats answer.
But in my design I can't doing this, because I has been wrong at the first time.
And the greats answer was from Mr. #10676716 #GMB.
-- "top" table that stores the countries
create table countries (
country_id int primary key
name varchar(100)
);
-- the table that stores the divisions
create table divisions (
division_id int primary key,
country_id int references countries(country_id),
name varchar(100)
);
-- the table that stores the subdivisions
-- this corresponds to "table1" in your question
create table subdivisions (
subdivision_id int primary key,
division_id int references divisions(division_id),
name varchar(100)
);
-- the table that stores the reports
-- this corresponds to "table2" in your question
create table reports (
report_id int primary key,
division_id references divisions(division_id),
name varchar(100)
);
Thanks again Mr. GMB.

How do i fill my table with data from 3 different tables?

So I am working on a football world cup database. These are my important tables:
CREATE TABLE Countries(
Cid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE
);
CREATE TABLE Stadiums(
Sid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE,
Cid INT REFERENCES Countries NOT NULL
);
CREATE TABLE Groups(
Gid SERIAL PRIMARY KEY,
Name VARCHAR(64) NOT NULL,
TYear SMALLINT REFERENCES Tournaments NOT NULL
);
CREATE TABLE Teams(
Tid SERIAL PRIMARY KEY,
Cid INT REFERENCES Countries NOT NULL,
Gid INT REFERENCES Groups NOT NULL
);
CREATE TABLE Matches(
Mid INT PRIMARY KEY,
HomeTid INT REFERENCES Teams NOT NULL,
VisitTid INT REFERENCES Teams NOT NULL,
HomeScore SMALLINT NOT NULL,
VisitScore SMALLINT NOT NULL,
MatchDate DATE NOT NULL,
MatchType VARCHAR(64) NOT NULL,
Sid INT REFERENCES Stadiums NOT NULL
);
CREATE TABLE tempmatches(
year INTEGER,
host_country VARCHAR(255),
match_id INTEGER,
type VARCHAR(255),
date DATE,
location1 VARCHAR(255),
team1 VARCHAR(255),
team2 VARCHAR(255),
score1 INTEGER,
score2 INTEGER
);
so my current problem is that I need to populate the columns HomeTid and VisitId of the Matches table with the tid's from the team's table that corresponds with the country of that team from the countries table but I'm not sure how to do that. I tried a few queries but none of them seemed to work. Has anyone an idea on how to solve this?
Using JOIN keyword you can combine 2 tables data.
Here, in this case, you have to use 3-way join.
Eg:
3-way JOIN can be used in this way:
SELECT * FROM table1 JOIN table2 ON table1.col1=table2.col2 JOIN table3 ON table3.col3=table.col1;
Here the 2 tables will get joined based on the columns mentioned after the "ON" keyword.
Here is a reference link in which JOIN is explained clearly
https://www.w3schools.com/sql/sql_join.asp
Use JOIN operation. In SQL it helps to combine several tables(queries) in one

SQL Server 2012 : Create Table

CREATE TABLE Schedule
(
Section DATETIME NOT NULL PRIMARY KEY(CourseID, Section, EmployeeID),
CourseID VARCHAR(10) REFERENCES Course(CourseID) NOT NULL,
EmployeeID VARCHAR(20) NOT NULL REFERENCES Employee(EmployeeID),
StartTime TIME NULL,
Days DATE NULL,
Length TIME NULL
)
CREATE TABLE Enrollment
(
StudentID INT Primary key (StudentID, CourseID, Section) NOT NULL,
CourseID VARCHAR(10) REFERENCES Course(CourseID) NOT NULL,
Section DATETIME NOT NULL REFERENCES Schedule(Section)
)
2nd table did not get created, where did I go wrong?
Its because you made the primary key in the Schedule table a natural/combined key.
Try creating a stand alone column for this purpose instead. I've included an example below that shows the differences.
CREATE TABLE DBO.PK_TEST (
Col_A INT NOT NULL
,Col_B INT NOT NULL
,Primary Key(Col_A,Col_B)
)
Create table DBO.PK_TEST_2 (
Col_A int NOT NULL
,Col_B int NOT NULL
,Col_C as (cast(Col_A as nvarchar)
+ cast(Col_B as nvarchar)) PERSISTED NOT NULL
,primary key(Col_C)
)

SQL Relation, one-to-many with a current used row

in sql i have a table of items. An item can have multiples prices. But when i come to using the data, most of the time i only need the currentPrice that i can find with the date.
My question : Would it be wrong to have 2 relation on price where and Item would have a relation with the currentPrice and all the price. Do there is a solution for this kind of problem to prevent complication in my mvc. Im currently using a viewModel with and the current price but if i could handle this in the database it seem better to me. (tell me if its not).
Note: I don't think this exact methode would work since I would need to create my price table before my item table and the same for the item table. But this show my problem.
Thanks alot for your help.
CREATE TABLE Item.Items
(
ItemId INT NOT NULL
CONSTRAINT PK_Items_ItemId
PRIMARY KEY
IDENTITY,
--------------------------------------------------
--CurrentPriceId INT NOT NULL
CONSTRAINT FK_Prices_Items
FOREIGN KEY REFERENCES Item.Items (ItemId),
--------------------------------------------------
Name VARCHAR(100) NOT NULL,
Points INT NOT NULL DEFAULT 0,
Description VARCHAR(5000) NULL
)
CREATE TABLE Item.Prices
(
PriceId INT NOT NULL
CONSTRAINT PK_ItemPrices_ItemPriceId
PRIMARY KEY
IDENTITY,
ItemId INT NOT NULL
CONSTRAINT FK_ItemPrices_Item
FOREIGN KEY REFERENCES Item.Items (ItemId),
EffectiveDate DATETIME NOT NULL,
Value MONEY NOT NULL
)
better would be:
CREATE TABLE Item.Items
(
ItemId INT NOT NULL
CONSTRAINT PK_Items_ItemId
PRIMARY KEY IDENTITY,
--------------------------------------------------
CurrentPrice MONEY NOT NULL, -- optional optimization, redundant as
-- current price is available from item.Prices
--------------------------------------------------
Name VARCHAR(100) NOT NULL,
Points INT NOT NULL DEFAULT 0,
Description VARCHAR(5000) NULL
)
CREATE TABLE Item.Prices
(
ItemId INT NOT NULL
CONSTRAINT FK_ItemPrices_Item
FOREIGN KEY REFERENCES Item.Items (ItemId),
EffectiveUtc DATETIME NOT NULL,
Price MONEY NOT NULL,
Constraint [ItemPricesPK] PRIMARY KEY CLUSTERED
(
[ItemId] ASC,
[EffectiveUtc] ASC
)
)
As mentioned by #popovitz, you can always get the price as of any specific date using a correlated subquery ...
Select i.name, p.price
From Item.Items i
Join Item.Prices p
ON i.ItemId = p.ItemId
Where p.EffectiveUtc =
(Select Max(EffectiveUtc )
From Item.Prices
Where ItemId = i.ItemId
And EffectiveUtc <= #asOfDate)
I would not recommend adding a currentPrice column, because you would have to constantly make sure that the item table is being updated whenever there a new price becomes effective. It's not that hard to query the current price when you have a table that contains the prices with an EffectiveDate column:
SELECT i.name, p.price FROM Items i
INNER JOIN Prices p ON i.ItemId = p.ItemId
WHERE p.EffectiveDate =
(SELECT MAX(EffectiveDate) FROM Price
WHERE EffectiveDate <= SYSDATE
AND ItemId = i.ItemId)
This will select the correct price for the current system time, assuming that (EffectiveDate, ItemId) is unique for the table prices.

SQL Logic and Aggregate Issue

I have the following problem to solve in SQL :
d) A query that provides management information on take up of the various types of activities on offer. For each type of activity, the query should show the total number of individuals who took that type of activity and the average number of individuals taking each type of activity.
Here are my tables :
CREATE TABLE accommodations
(
chalet_number int PRIMARY KEY,
chalet_name varchar(40) NOT NULL,
no_it_sleeps number(2) NOT NULL,
indivppw number(4) NOT NULL
)
CREATE TABLE supervisors
(
supervisor_number int PRIMARY KEY,
supervisor_forename varchar(30) NOT NULL,
supervisor_surname varchar(30) NOT NULL,
mobile_number varchar(11) NOT NULL
)
CREATE TABLE visitors
(
visitor_ID int PRIMARY KEY,
group_ID int NOT NULL,
forename varchar(20) NOT NULL,
surname varchar(20) NOT NULL,
dob date NOT NULL,
gender varchar(1) NOT NULL
)
CREATE TABLE activities
(
activity_code varchar(10) PRIMARY KEY,
activity_title varchar(20) NOT NULL,
"type" varchar(20) NOT NULL
)
CREATE TABLE "groups"
(
group_ID int PRIMARY KEY,
group_leader varchar(20) NOT NULL,
group_name varchar(30)
number_in_group number(2) NOT NULL
)
CREATE TABLE bookings
(
group_ID int NOT NULL,
start_date date NOT NULL,
chalet_number int NOT NULL,
no_in_chalet number(2) NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
CONSTRAINT bookings_pk PRIMARY KEY(group_ID, chalet_number));
CREATE TABLE schedule
(
schedule_ID int PRIMARY KEY,
activity_code varchar(10) NOT NULL,
time_of_activity number(4,2) NOT NULL,
am_pm varchar(2) NOT NULL,
"date" date NOT NULL
)
CREATE TABLE activity_bookings
(
visitor_ID int NOT NULL,
schedule_ID int NOT NULL,
supervisor_number int NOT NULL,
comments varchar(200),
CONSTRAINT event_booking_pk PRIMARY KEY(visitor_ID, schedule_ID));
ALTER TABLE visitors
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE Schedule
ADD FOREIGN KEY (activity_code)
REFERENCES activities(activity_code)
ALTER TABLE bookings
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE bookings
ADD FOREIGN KEY (chalet_number)
REFERENCES accommodations(chalet_number)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (visitor_ID)
REFERENCES visitors(visitor_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (schedule_ID)
REFERENCES schedule(schedule_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (supervisor_number)
REFERENCES supervisors(supervisor_number)
I have the following solution:
SELECT activities."type", 'overalltotal' AS OT, ('overalltotal' / 'activities') AS AVG
FROM activities, schedule
WHERE 'overalltotal' = (SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type"
)
AND 'activities' = (SELECT COUNT(DISTINCT activities."type")
FROM activities
)
AND schedule.activity_code = activities.activity_code
GROUP BY activities."type";
I have implemented sample data and code to check the variables above:
SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type";
Result : 20
SELECT COUNT(DISTINCT activities."type")
FROM activities;
Result : 5
However when running the code :
ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause:
*Action:
EDIT:
Using Dave's Code i have the following output:
Snowboarding 15
sledding 19
Snowmobiling 6
Ice Skating 5
Skiing 24
How would i do the final part of the question?
and the average number of individuals taking each type of activity.
You must use double quotes around column names in Oracle, not single quotes. For example, "overalltotal". Single quotes are for text strings, which is why you're getting an invalid number error.
EDIT: This is probably the type of query you want to use:
SELECT activities."type", COUNT(*) AS total, COUNT(*)/(COUNT(*) OVER ()) AS "avg"
FROM activities a
JOIN schedule s ON a.activity_code=s.activity_code
JOIN activity_bookings ab ON s.schedule_ID=ab.schedule_ID
GROUP BY activities."type";
Basically, because each activity booking has one visitor id, we want to get all the activity bookings for each activity. We have to go through schedule to do that. They we group the rows by the activity type and count how many activity bookings we have for each type.