Internal database summation - mysql

So basically I have this table Class_Sumations where I need to come up with some way to calculate the sum of the NumberofClassesTaken and the AmountPaid columns from the other tables...into the respectful columns in the last table.
The NumberofClassesTaken column would just sum all the classes the Client took and give a number. The AmountPaid column would sum all the dollar amounts spent on classes by a given client and give a total.
So for example Client 1 could have taken 2 yoga classes and paid $200 total so the NumberofClassesTaken would show 2, and the AmountPaid column would show 100.
I tried doing SELECT and sum but I always get the
Error code 1064, SQL state 42000: You have an error in your SQL syntax
thrown back at me.
Can anyone point me in the right direction here? (Keep in mind I'm relatively new to this so if you have some documentation to what you're suggesting that would be awesome too)
PS: I omitted the TRAINER table because it is a separate total from the club classes so you can ignore that foreign key in CLUB_CLASSES.
CREATE TABLE CLIENT(
ClientNumber INT(50) NOT NULL,
ClientLastName VARCHAR(50) NOT NULL,
ClientFirstName VARCHAR(50) NOT NULL,
ClientPhone VARCHAR(50) NOT NULL,
ClientEmail VARCHAR(50) NOT NULL,
ClientState VARCHAR(50) NOT NULL,
ClientCity VARCHAR(50) NOT NULL,
ClientStreet VARCHAR(50) NOT NULL,
ClientAddress VARCHAR(50) NOT NULL,
ClientZipCode INT NOT NULL,
PRIMARY KEY (ClientNumber));
INSERT INTO CLIENT
VALUES
('1','Marget','Michael','7703399207','MM#gmail.com',
'Kentucky','Merlin','Wending Way','312 Wending Way','30144');
INSERT INTO CLIENT
VALUES
('2','Squarepants','Spongebob','7701274532','SS#gmail.com',
'Kentucky','Merlin','Pineapple Under the Sea Way',
'856 Pineapple Under the Seas Way','30122');
CREATE TABLE CLUB_CLASSES(
ClassID INT(50) NOT NULL,
InstructorTrainerID INT(50) NOT NULL,
ClassName VARCHAR(50) NOT NULL,
ClassStartDate date NOT NULL,
ClassEndDate date NOT NULL,
ClassCost VARCHAR(50) NOT NULL,
PRIMARY KEY(ClassID),
FOREIGN KEY (InstructorTrainerID) REFERENCES TRAINER(TrainerID));
INSERT INTO CLUB_CLASSES
VALUES ('3501','1154','Yoga','1/3/13','1/5/13','100');
INSERT INTO CLUB_CLASSES
VALUES ('3502','2856','Pillate','1/3/13','2/5/13','50');
CREATE TABLE CLASS_SUMMATIONS(
ClassID INT(50) NOT NULL,
ClientID INT(50) NOT NULL,
NumberofClassesTaken VARCHAR(50) NOT NULL,
AmountPaid VARCHAR(50) NOT NULL,
PRIMARY KEY(ClassID, ClientNumber),
FOREIGN KEY(ClientNumber) REFERENCES CLIENT(ClientNumber));
INSERT INTO CLIENT_SUMMATIONS (
'3501','1',
'SELECT SUM(CLUB_CLASSES.ClassID','SELECT SUM(CLUB_CLASSES.ClassCost)');
INSERT INTO CLIENT_SUMMATIONS('3502','2','xxx','xxxx');

Related

How to represent float values in SQL

I'm trying to create a database in Ubuntu using MySQL in the command line, I need to create a table with the following data:
CREATE TABLE Vehicles (
Vehicle_ID int NOT NULL,
Vehicle_Type VARCHAR(255) NOT NULL,
Model_name VARCHAR(255) NOT NULL,
Engine_Size float(1,1) NOT NULL,
Condition VARCHAR(255) NOT NULL,
Price float(9,2) NOT NULL,
PRIMARY KEY (Vehicle_ID)
);
It just returns an error that says "ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Condition varchar(255) NOT NULL,
Price float(9,2) NOT NULL,
PRIMARY KEY (Vehicle' at line 6"
What is wrong with my code? The "Price" and "Engine_Size" columns need to only be a float/decimal values so they can't be varchar because I want to only be able to insert numbers.
This works:
CREATE TABLE Vehicles (
Vehicle_ID int NOT NULL,
Vehicle_Type VARCHAR(255) NOT NULL,
Model_name VARCHAR(255) NOT NULL,
Engine_Size int NOT NULL,
Vehicle_Condition VARCHAR(255) NOT NULL,
Price numeric(9,2) NOT NULL,
PRIMARY KEY (Vehicle_ID)
);
Notes:
For Price you seem to want numeric, not float, because you are specifying the precision and scale.
For Engine_Size, I have no idea what float(1, 1) is supposed to mean. I am guessing that int is an appropriate type.
Condition is a reserved word in MySQL, so I changed the name of the column.
The only apparent problem in your code is the use of 'condition' as a column name as condition is a reserved word in MySQL.
You can fix it in 2 ways:
Don't use 'condition' as a column name:
CREATE TABLE Vehicles (
Vehicle_ID int NOT NULL,
Vehicle_Type VARCHAR(255) NOT NULL,
Model_name VARCHAR(255) NOT NULL,
Engine_Size float(1,1) NOT NULL,
V_Condition VARCHAR(255) NOT NULL, //Just an example feel free to use any another name
Price float(9,2) NOT NULL,
PRIMARY KEY (Vehicle_ID)
);
Put 'condition' inside backticks (``)
CREATE TABLE Vehicles (
Vehicle_ID int NOT NULL,
Vehicle_Type VARCHAR(255) NOT NULL,
Model_name VARCHAR(255) NOT NULL,
Engine_Size float(1,1) NOT NULL,
`Condition` VARCHAR(255) NOT NULL,
Price float(9,2) NOT NULL,
PRIMARY KEY (Vehicle_ID)
);
Hope this helps

MySQL database schema: 3 columns of same type with different purpose

I am building a financial app, and it requires the following tables:
tax
item, which can have one tax
invoice, which can have many items
To the question:
An invoice must have the ability to contain 3 categories of emails:
Recipient emails
CC emails
BCC emails
So far I just have a recipients/cc/bcc column, but I don't think it's good because I'd basically have to concatenate the emails together and separate them by a comma or something.
I also thought about a generic email table, but then I'd have to create invoice_recipient_email, invoice_cc_email and invoice_bcc_email tables respectively, in order to link the emails back to the particular invoice ID as well as categorize them by the 3 types.
Can someone advice me on my second solution, or provide a better way to do this?
Here is my current schema:
CREATE TABLE tax (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
rate INT(3) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE item (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
description VARCHAR(1000) NOT NULL,
quantity INT(10) NOT NULL,
price INT(10) NOT NULL,
CONSTRAINT `f_tax_item_tax_id` FOREIGN KEY (`tax_id`) REFERENCES `tax` (`id`),
PRIMARY KEY (id)
);
CREATE TABLE invoice (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
invoice_number VARCHAR(255) NOT NULL,
recipients VARCHAR(1000) NOT NULL,
cc VARCHAR(1000) NOT NULL,
bcc VARCHAR(1000) NOT NULL,
discount INT(10) NOT NULL,
note VARCHAR(500) NOT NULL,
terms VARCHAR(2000) NOT NULL,
due_date TIMESTAMP NOT NULL,
PRIMARY KEY (id)
);
I would add a single recipients table with id (pk), invoice_id (fk), email, recipient_type fields, where recipient type could have one of the following values: to, cc, or bcc. The recipient type field would tell you how to use the email address, therefore you would not need 3 separate tables to hold the 3 different recipient types.
1 record would hold only 1 email address.
You can normalize your emails into a single table and put a flag on it to categorize its type.
CREATE TABLE invoice (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
invoice_number VARCHAR(255) NOT NULL,
discount INT(10) NOT NULL,
note VARCHAR(500) NOT NULL,
terms VARCHAR(2000) NOT NULL,
due_date TIMESTAMP NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE email(
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
invoice_id INT(10) not null references invoice(id),
email_type int not null,
addresses varchar(1000),
PRIMARY KEY (id)
);
You can define your email types in another table as well. You can look at this approach implemented in a production environment for phone numbers in MSSSQL but same concept. We however normalize the records to one phone number per record which I would also recommend you do.
CREATE TABLE [dbo].[ActorPhones](
[PKId] [int] IDENTITY(0,1) NOT NULL Primary Key,
[FKActorId] [int] NOT NULL References Actor(PKID),
[FKPhoneTypeId] [int] NOT NULL,
[Number] [varchar](20) NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[PhoneTypes](
[PKId] [int] IDENTITY(0,1) NOT NULL Primary Key,
[PhoneTypeName] [varchar](50) NOT NULL References ActorPhones(PKId),
[PhoneTypeDescription] [varchar](250) NULL,
[ModifiedDate] [datetime] NULL,
[ModifiedBy] [varchar](50) NULL
)

VIEW created in MySQL giving wrong output with SELECT

I'm creating a database for a courtier company and I have 5 relations
CREATE TABLE Customer
(
cid int(7) NOT NULL,
cfname char(25) NOT NULL,
clname char(25) NOT NULL,
aptnum int(100) NOT NULL,
street char(50) NOT NULL,
pobox int(10) NOT NULL,
area char(50) NOT NULL,
country char(50) NOT NULL,
phone int(12) NOT NULL,
PRIMARY KEY (cid)
)ENGINE=INNODB;
CREATE TABLE Orderr
(
orderid int(8) NOT NULL,
origin char(100) NOT NULL,
destination char(100) NOT NULL,
eta date NOT NULL,
weight int(100) NOT NULL,
priority enum('F','R') NOT NULL,
task enum('P','D') NOT NULL,
odate date NOT NULL,
cnum int(12) NOT NULL,
cpin int(8) NOT NULL,
custid int(7) NOT NULL,
PRIMARY KEY (orderid),
FOREIGN KEY (custid) REFERENCES Customer(cid)
)ENGINE=INNODB;
CREATE TABLE History
(
histid int(6) NOT NULL,
orderid int(8) NOT NULL,
status enum('D','O','R') NOT NULL,
current_loc char(50) NOT NULL,
PRIMARY KEY(histid),
FOREIGN KEY (orderid) REFERENCES Orderr(orderid)
)ENGINE=INNODB;
CREATE TABLE Driver
(
driverid int(6) NOT NULL,
dfname varchar(25) NOT NULL,
dlname varchar(25) NOT NULL,
dob date NOT NULL,
phone int(10) NOT NULL,
vehicle int(6) NOT NULL,
PRIMARY KEY (driverid)
)ENGINE=INNODB;
CREATE TABLE Vehicle
(
vid int(6) NOT NULL,
num_plate varchar(6) NOT NULL,
vtype enum('T','B','P') NOT NULL,
driverr int(6) NOT NULL,
orders int(8) NOT NULL,
PRIMARY KEY (vid),
FOREIGN KEY (driverr) REFERENCES Driver(driverid),
FOREIGN KEY (orders) REFERENCES Orderr(orderid)
)ENGINE=INNODB;
I am trying to create a VIEW for the Customer giving access to specific columns, here is the query
CREATE VIEW CustView AS
SELECT cfname, clname, aptnum, street, pobox, area, country, origin, destination, weight, priority, task, eta, odate, dfname, dlname, driver.phone
FROM Customer, Orderr, Vehicle, Driver
WHERE Customer.cid=Orderr.custid AND Vehicle.driverr=Driver.driverid AND Orderr.orderid=Vehicle.orders;
When I run SELECT * FROM CustView I do not get the desired output. What changes if any should I make to my query or perhaps to my relations?
Thanks.
As the previous posters remarked, I can only guess. But from your table and view definition, I get the suspicion that you didn't model the relation between Vehicle and Order properly. A Vehicle can be used for many Orders, right? In this case, the Vehicle id must be a foreign key in the Order table. Your design is just the other way round.
Not related to your question, I am suspicious of your History table. The history of orders fulfilled comprises just those orders which are in the past, right? So the history would be just a view that selects orders by past values of some of the dates contained therein.

How to select column twice from the same mysql table?

I've been doing quite a bit of MySql lately for uni, and i cant seem to figure out how to get a field from a table twice in the same statement.
My database is this:
drop database if exists AIRLINE;
create database AIRLINE;
use AIRLINE;
CREATE TABLE AIRCRAFT
(
AircraftNo INT(20) NOT NULL,
AircraftType VARCHAR(100) NOT NULL,
FuelBurn VARCHAR(100) NOT NULL,
Airspeed VARCHAR(100) NULL,
LastInspection DATE NULL,
TotalFlyingTime INT(50) NOT NULL,
TotalTimeLeftEngine INT(50) NULL,
TotalTimeRightEngine INT(50) NULL,
PRIMARY KEY (AircraftNo)
);
CREATE TABLE PILOT
(
PilotCode INT(20) NOT NULL,
LastName VARCHAR(100) NOT NULL,
FirstName VARCHAR(100) NOT NULL,
MiddleInitial VARCHAR(50) NULL,
HiredDate DATE NULL,
BasePay VARCHAR(50) NULL,
Dependents VARCHAR(100) NULL,
License INT(50) NOT NULL,
TotalHours INT(50) NOT NULL,
PRIMARY KEY (PilotCode)
);
CREATE TABLE CUSTOMER
(
CustomerNo INT(20) NOT NULL,
Name VARCHAR(100) NOT NULL,
Contact INT(50) NOT NULL,
Phone INT(50) NOT NULL,
Street VARCHAR(100) NULL,
Suburb VARCHAR(100) NULL,
State VARCHAR(100) NULL,
Postcode INT(20) NULL,
Balance INT(50) NULL,
PRIMARY KEY (CustomerNo)
);
CREATE TABLE CHARTER
(
TripTicket INT(50) NOT NULL AUTO_INCREMENT,
CharterDate DATE NOT NULL,
PilotCode INT(20) NOT NULL,
CopilotCode INT(20) NULL,
AircraftNo INT(20) NOT NULL,
Destination VARCHAR(100) NOT NULL,
Distance INT(20) NULL,
HoursFlow INT(20) NULL,
HoursWating INT(20) NULL,
Fuel INT(20) NULL,
Oil INT(20) NULL,
CustomerNo INT(20) NOT NULL,
PRIMARY KEY (TripTicket),
FOREIGN KEY(PilotCode) REFERENCES PILOT(PilotCode),
FOREIGN KEY(CopilotCode) REFERENCES PILOT(PilotCode),
FOREIGN KEY(AircraftNo) REFERENCES AIRCRAFT(AircraftNo),
FOREIGN KEY(CustomerNo) REFERENCES CUSTOMER(CustomerNo)
);
My goal is to list the charterdate, destination, customer details (name, customerNo, address, phone), and pilot names (firstname, middleinitial, lastname) of all charters.
I have managed to get everything, but only with one pilot. I need to list both pilot names however.
I have googled my problem, but i cant seem to find anything.
If someone could please point me in the right direction, i would be hugely grateful.
Thanks
Cheers
Corey
You just need to JOIN the table twice with different aliases.
Something like:
SELECT p1.lastname, p2.lastname, /* other fields */
FROM CHARTER c
JOIN PILOT p1 ON p1.PilotCode = c.PilotCode
JOIN PILOT p2 on p2.PilotCode = c.CoPilotCode
Give alias name as
SELECT a.columname1 AS 1, a.columname1 AS 2
FROM tablename a
You have to use table aliases in your join:
SELECT MainPilot.LastName, CoPilot.LastName FROM CHARTER
LEFT JOIN PILOT MainPilot ON MainPilot.PilotCode=CHARTER.PilotCode
LEFT JOIN PILOT CoPilot ON CoPilot.PilotCode=CHARTER.CoPilotCode
You need to join the pilot table twice in your query. to do that you will have to use an alias for each Pilot table you join.
You can simply use the same column multiple times and add for each of them and as and use different name
SELECT column1 as c1, column1 as c2, column1 as c3 FROM TABLE1 WHERE ....

Split non-relational table into multiple relational tables

I have the following table of 60000 rows, in a MySQL 5 database, which is derived from a CSV file:
CREATE TABLE `smts_import` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`AscCode` varchar(5) NOT NULL,
`AscName` varchar(50) NOT NULL,
`RgnCode` varchar(5) NOT NULL,
`RgnName` varchar(100) NOT NULL,
`SCode` varchar(30) NOT NULL,
`SName` varchar(100) NOT NULL,
`AM` int(11) NOT NULL,
`AF` int(11) NOT NULL,
`LG` decimal(10,4) NOT NULL,
`LT` decimal(10,4) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ars_codes` (`AscCode`,`RgnCode`,`SCode`),
KEY `s_code` (`SCode`)
);
and which contains much repeated data. SCodes are unique, and the relationship between the RgnCode and SCode fields is many-to-one, as is that between the AscCode and RgnCode fields.
I want to split up (normalize) the data into three separate tables in a relational manner, such that no data are repeated:
CREATE TABLE `ascs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`a_code` varchar(6) NOT NULL,
`a_name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `a_code` (`a_code`)
);
CREATE TABLE `rgns` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`a_id` int(11) NOT NULL,
`r_code` varchar(6) NOT NULL,
`r_name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `a_id`+`r_code` (`a_id`, `r_code`),
KEY `r_code` (`r_code`)
);
CREATE TABLE `sms` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`r_id` int(11) NOT NULL,
`s_code` varchar(16) NOT NULL,
`s_name` varchar(100) NOT NULL,
`a_m` int(11) NOT NULL,
`a_f` int(11) NOT NULL,
`lg` decimal(10,4) NOT NULL,
`lt` decimal(10,4) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `r_id+s_code` (`r_id`,`s_code`),
KEY `s_code` (`s_code`)
);
where rgns.a_id is a foreign key on ascs.id, and sms.r_id is a foreign key on rgns.id.
I've created the three tables and successfully populated the first two, ascs and rgns, with unique data from the smts_import table. My problem comes when I try to populate the third table sms with just the SCode, SName, AM, AF, LG and LT fields from the smts_import table, PLUS the appropriate id from the rgns table. And here I just get lost, I've tried many variations on the following:
INSERT INTO sms (r_id, s_code, s_name, a_m, a_f, lg, lt)
SELECT DISTINCT sr.id, SCode, SName, AM, AF, LG, LT
FROM sms_import AS si, rgns AS sr, ascs AS sa
WHERE (sr.r_code = si.RgnCode)
AND (sr.a_id = sa.id)
AND (sa.a_code = si.AscCode)
ORDER BY SCode
but I just end up with too many records. How do I write this insert statement to get the appropriate fields from all records from the sms_import table, plus the correct values in the sms.r_id field from the rgns.id field?
Thanks for your help
"the relationship between the RgnCode and SCode fields is many-to-one"
So you also get many rgns.id per SCode.
If you select distinct rgns.id, SCode, etc. you will get each SCode more than once depending on how many RgnCode you have for it.
I would suggest adding a id column to the sms table and create a separate table sms2rgns which contains the one-to-many relations sms.id -> rgns.id