Insert does not work with cursor - sql

I have a problem that my Insert statement doesn't work. I created temp tables, then the insert statement is working based on two columns in this temp tables.
The data exists in the temp tables, but the insert is not working with no error appearing. Thanks in advance
DECLARE JPCUSTOMER_CURSOR CURSOR FOR
SELECT
cu.CustomerNo, jp.ID
FROM
CUSTOMERNO# cu, SalesmanNo# sa, JourneyPlan JP
WHERE
cu.OCCURRENCE = sa.OCCURRENCE
AND jp.AssignedTO = sa.SalesmanNo
OPEN JPCUSTOMER_CURSOR
FETCH NEXT FROM JPCUSTOMER_CURSOR INTO #CUST_ID,#JP_ID
WHILE (##FETCH_STATUS = 0)
BEGIN
INSERT INTO [JPCustomer] ([CustomerID ], [JPID], [Frequency], [StartWeek],
[sat], [sun], [mon], [tue], [wed], [thu], [fri],
[VisitOrder], [ModifiedOn], [ModifiedBy],
[CreatedOn], [Createdby],
[RecordSource], [IsPotential])
VALUES (#CUST_ID, #JP_ID, 4, 1,
1, 1, 1, 1, 1, 1, 1,
NULL, NULL, NULL,
NULL, NULL, 0, 0)
END
CLOSE JPCUSTOMER_CURSOR;
DEALLOCATE JPCUSTOMER_CURSOR;

You don't need a cursor for what you are doing. This will be much faster:
INSERT INTO [JPCustomer] ([CustomerID ],
[JPID],
[Frequency],
[StartWeek],
[sat],
[sun],
[mon],
[tue],
[wed],
[thu],
[fri],
[VisitOrder],
[ModifiedOn],
[ModifiedBy],
[CreatedOn],
[Createdby],
[RecordSource],
[IsPotential])
select cu.CustomerNo,
jp.ID,
4,
1,
1,
1,
1,
1,
1,
1,
1,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
0
from CUSTOMERNO# cu
join SalesmanNo# sa on cu.OCCURRENCE = sa.OCCURRENCE
join JourneyPlan JP on jp.AssignedTO = sa.SalesmanNo

You don't need and shouldn't use a cursor for this. Just an INSERT ... SELECT. EG
with q as
(
select cu.CustomerID CUST_ID, jp.ID JPID
from CUSTOMERNO# cu
join SalesmanNo# sa
on cu.OCCURRENCE = sa.OCCURRENCE
join JourneyPlan JP
on jp.AssignedTO = sa.SalesmanNo
)
INSERT INTO [JPCustomer] ([CustomerID],
[JPID],
[Frequency],
[StartWeek],
[sat],
[sun],
[mon],
[tue],
[wed],
[thu],
[fri],
[VisitOrder],
[ModifiedOn],
[ModifiedBy],
[CreatedOn],
[Createdby],
[RecordSource],
[IsPotential])
SELECT CustomerID,
JPID,
4,
1,
1,
1,
1,
1,
1,
1,
1,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
0
from q;

Related

How can I put SELECT result set to SELECT column?

I have two tables: Job(ID,Name, etc.) and Address(ID, Job_ID, Name etc). I want to get result like this:
[
{
"Job_ID": 1,
"JobName": "Test",
"Addresses": [
{
"ID": 1,
"Name": "King street"
},
{
"ID": 2,
"Name": "Queen`s street
}
]
}
]
My current query that gets only one address for a job looks like this:
SELECT TOP 100
JO.ID,
JO.Closed as Deleted,
JO.Number as JobNumber,
JO.Name as JobName,
Convert(date, JO.Start_Date) as Start_Date,
JO.Job_Status_ID as Status,
A.ID as Address_ID,
A.Name as Name,
A.Number as Number,
A.Sort_Name as Sort_Name,
A.Address_1 as Address_1,
A.Address_2 as Address_2,
A.ZipCode as ZIP,
A.E_Mail_Address as Email,
A.Web_Site_URL as Web_Site_URL,
A.TAXRATE as Tax_Rate,
A.State
FROM Job JO
INNER JOIN Address A ON A.Job_Id = JO.ID
Is it possible without pivot table(Address_ID, Job_ID)?
You can use FOR JSON to convert you results to JSON. This gives the result you are looking for:
CREATE TABLE #Job (ID INT NOT NULL, Name VARCHAR(50));
INSERT #Job (ID, Name)
VALUES (1, 'Job 1'), (2, 'Job 2');
CREATE TABLE #Address (ID INT NOT NULL, JobID INT NOT NULL, Name VARCHAR(50));
INSERT #Address (ID, JobID, Name)
VALUES (1, 1, 'King street'), (2, 1, 'Queen''s street'), (3, 2, 'Address 3'), (4, 2, 'Address 4');
SELECT JobID = j.ID,
JobName = j.Name,
Addresses = ( SELECT a.ID, a.Name
FROM #Address AS a
WHERE a.JobID = j.ID
FOR JSON AUTO
)
FROM #Job AS j
FOR JSON AUTO;

Insert null value

I'm trying to Insert a double precision (ilosc_zlec) value into a table (M_ZAMWLASNEPOZ). First I use a select statement to get the value. After I run this part of code, I can see the correct value in the variable ( 39 ). Next I'm trying to insert the selected values in the table and most of them get inserted but field ILOSC with should become the value of ilosc_zlec shows NULL. Both ILOSC, ilosc_zlec are double precision variables.
for select t.strumet_katzw,a.kategoria,a.rok_zam,a.symbol_zam,a.indeks,a.nazwa,a.wyroznik,a.ilosc_zlec,a.lp_zam from m_zlecenia a
left join m_przewod_gl g
on g.kat_zlec= a.kategoria and g.rok_zlec= a.rok_zam and g.symb_zlec= a.symbol_zam and g.lp_zlec= a.lp_zam
left join m_przewod_op p
on p.kat_zlec= a.kategoria and p.rok_zlec= a.rok_zam and p.symb_zlec= a.symbol_zam and p.lp_zlec= a.lp_zam and p.nr_przew=g.nr_poz
left join m_kot t
on t.kod_oper= p.kod_oper
where a.wyroznik=:wyroznik and a.grupa_zl= 'KOP' and a.data_wykon is null and f_mid(p.kod_oper,1,4)='KOOD' and t.strumet_katzw is not null
into: strumet_katzw,:kategoria, :rok_zam, :symbol_zam, :indeks, :nazwa, :wyroznik, :ilosc_zlec,:lp_zam
do begin
select symbol_zam from m_zamwlasne where kategoria=:strumet_katzw and F_MID(symbol_zam,1,8) = (:symbol_zam||f_mid(:indeks,5,3)) into: symb_szukan_nagl ;
-- wypelniasz pozycje naglowka
INSERT INTO M_ZAMWLASNEPOZ (KATEGORIA, ROK_ZAM, SYMBOL_ZAM, LP_ZAM, INDEKS, ILOSC, TERMIN, CENA_ZAM, POBRANO_IL, ZREALIZOWANO, DATA_ZM, OPER, KOD_KONTRO, ZAKUP_DLA, NA_PRZEWOD, IL_PO_KONTROLI, JM, ILOSC_ZAK, REL_JM_ZAK, NR_ZAPOTRZEB, DATA_POTW, OPIS_POZ2, OPIS_POZ, KOOP_WYROB, KOOP_WYROB_ILOSC, POBRANO_KOOP, SKAD_KOPIA, TYP_INDEKSU, SUMA_DOST, DATA_REALIZ, LP_OFERTY, KONTO_KOSZT, NA_NADRZ, PRZEDMIOT, RABAT, PR_RABAT, CENA_JEDN, LP_OPER, ILOSC_REJOP_KOOP, ROZLICZONE)
VALUES (:strumet_katzw, :rok_zam, :symb_szukan_nagl, :lp_zam, :indeks, :ilosc_zlec, 'now', 0, 0, 'T', 'now', user, 'NN', NULL, NULL, 0, 'SZT', 0, 0, NULL, 'NOW', NULL, NULL, NULL, 0, 0, NULL, 'I', 0, 'NOW', 1, NULL, NULL, 'a', 0, 0, 0, NULL, NULL, NULL);
suspend;
end

ORA-00933: SQL command not properly ended when inserting multiple rows [duplicate]

This question already has answers here:
inserting multiple rows with one insert command
(5 answers)
Closed 4 years ago.
I make a script that generates insert statements from SQL data. When I insert just one line of the insert it works but when I try to insert more than one row I get ORA-00933: SQL command not properly ended here is the insert statement:
This works by itself:
INSERT INTO CAMPAIGN (CAMPAIGN_ID, SHOP_ID, CAMPAIGN_TYPE, SORT_ORDER, STATUS, VALID_FROM, VALID_TILL, CREATED_AT, MODIFIED_AT, CUSTOM_GRID_LAYOUT_CSS, IMAGE_URL, KEY, SHOW_PRODUCTS_FILTER, MOBILE_APP_IMAGE_URL, LAYOUT_ID, SHOW_OWN_BRAND, VALIDATION_STATUS, CAMPAIGN_USAGE_ID, STORE_END_DATE, PAGING_ALLOWED, CAROUSEL_BUTTON_TEXT_COLOR, CAROUSEL_BUTTON_BG_COLOR, CAROUSEL_BUTTON1_LABEL, CAROUSEL_BUTTON1_URL, CAROUSEL_BUTTON2_LABEL, CAROUSEL_BUTTON2_URL, CAROUSEL_HTML_OVERLAY, MOBILE_APP_TEASER_URL, CAROUSEL_CLAIM_URL, CAROUSEL_HERO_URL, CAROUSEL_BOX_COLOR, AVOID_CAMPAIGN_NAV_TEASER, CAROUSEL_BUTTON1_NEW_TAB, CAROUSEL_BUTTON2_NEW_TAB, SALE_QUALIFICATION_ID, SALE_TARGET_CAMPAIGN) VALUES (CAMPAIGN_SEQ.nextval, 1, 'C', 0, 'A', to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2116-11-23', 'YYYY-MM-DD'), to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2018-07-02', 'YYYY-MM-DD'), null, null, null, 1, null, '5_COL', 0, null, 4, to_date('2116-11-23', 'YYYY-MM-DD'), 0, null, null, 'Artikel ab Mo., 02.12.', 'https://www.lidl.de', null, null, null, null, null, null, null, 0, 0, 0, null, 0);
Now I add another row to it separating it by a , character and ending the whole statement with a ; character.
INSERT INTO CAMPAIGN (CAMPAIGN_ID, SHOP_ID, CAMPAIGN_TYPE, SORT_ORDER, STATUS, VALID_FROM, VALID_TILL, CREATED_AT, MODIFIED_AT, CUSTOM_GRID_LAYOUT_CSS, IMAGE_URL, KEY, SHOW_PRODUCTS_FILTER, MOBILE_APP_IMAGE_URL, LAYOUT_ID, SHOW_OWN_BRAND, VALIDATION_STATUS, CAMPAIGN_USAGE_ID, STORE_END_DATE, PAGING_ALLOWED, CAROUSEL_BUTTON_TEXT_COLOR, CAROUSEL_BUTTON_BG_COLOR, CAROUSEL_BUTTON1_LABEL, CAROUSEL_BUTTON1_URL, CAROUSEL_BUTTON2_LABEL, CAROUSEL_BUTTON2_URL, CAROUSEL_HTML_OVERLAY, MOBILE_APP_TEASER_URL, CAROUSEL_CLAIM_URL, CAROUSEL_HERO_URL, CAROUSEL_BOX_COLOR, AVOID_CAMPAIGN_NAV_TEASER, CAROUSEL_BUTTON1_NEW_TAB, CAROUSEL_BUTTON2_NEW_TAB, SALE_QUALIFICATION_ID, SALE_TARGET_CAMPAIGN) VALUES
(CAMPAIGN_SEQ.nextval, 1, 'C', 0, 'A', to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2116-11-23', 'YYYY-MM-DD'), to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2018-07-02', 'YYYY-MM-DD'), null, null, null, 1, null, '5_COL', 0, null, 4, to_date('2116-11-23', 'YYYY-MM-DD'), 0, null, null, 'Artikel ab Mo., 02.12.', 'https://www.lidl.de', null, null, null, null, null, null, null, 0, 0, 0, null, 0),
(CAMPAIGN_SEQ.nextval, 1, 'P', 0, 'A', to_date('2016-11-09', 'YYYY-MM-DD'), to_date('2116-11-09', 'YYYY-MM-DD'), to_date('2016-11-09', 'YYYY-MM-DD'), to_date('2018-07-02', 'YYYY-MM-DD'), null, null, null, 0, null, '4_COL_LEFT_NAV', 1, null, null, null, 1, null, null, null, null, null, null, null, null, null, null, null, 0, 0, 0, null, 0);
The above one will give me the error. Correct me if I am wrong but inserting multiple rows is allowed like this, correct?
Use insert all.
Below is the example.
INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (20, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (21, 'Microsoft')
INTO suppliers (supplier_id, supplier_name) VALUES (22, 'Apple')
If you look at the syntax diagram in the documentation, you'll see that there is no reverse arrow after the closing paren for values.
Two solutions. Two inserts:
INSERT INTO CAMPAIGN (CAMPAIGN_ID, SHOP_ID, CAMPAIGN_TYPE, SORT_ORDER, STATUS, VALID_FROM, VALID_TILL, CREATED_AT, MODIFIED_AT, CUSTOM_GRID_LAYOUT_CSS, IMAGE_URL, KEY, SHOW_PRODUCTS_FILTER, MOBILE_APP_IMAGE_URL, LAYOUT_ID, SHOW_OWN_BRAND, VALIDATION_STATUS, CAMPAIGN_USAGE_ID, STORE_END_DATE, PAGING_ALLOWED, CAROUSEL_BUTTON_TEXT_COLOR, CAROUSEL_BUTTON_BG_COLOR, CAROUSEL_BUTTON1_LABEL, CAROUSEL_BUTTON1_URL, CAROUSEL_BUTTON2_LABEL, CAROUSEL_BUTTON2_URL, CAROUSEL_HTML_OVERLAY, MOBILE_APP_TEASER_URL, CAROUSEL_CLAIM_URL, CAROUSEL_HERO_URL, CAROUSEL_BOX_COLOR, AVOID_CAMPAIGN_NAV_TEASER, CAROUSEL_BUTTON1_NEW_TAB, CAROUSEL_BUTTON2_NEW_TAB, SALE_QUALIFICATION_ID, SALE_TARGET_CAMPAIGN)
VALUES (CAMPAIGN_SEQ.nextval, 1, 'C', 0, 'A', to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2116-11-23', 'YYYY-MM-DD'), to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2018-07-02', 'YYYY-MM-DD'), null, null, null, 1, null, '5_COL', 0, null, 4, to_date('2116-11-23', 'YYYY-MM-DD'), 0, null, null, 'Artikel ab Mo., 02.12.', 'https://www.lidl.de', null, null, null, null, null, null, null, 0, 0, 0, null, 0);
INSERT INTO CAMPAIGN (CAMPAIGN_ID, SHOP_ID, CAMPAIGN_TYPE, SORT_ORDER, STATUS, VALID_FROM, VALID_TILL, CREATED_AT, MODIFIED_AT, CUSTOM_GRID_LAYOUT_CSS, IMAGE_URL, KEY, SHOW_PRODUCTS_FILTER, MOBILE_APP_IMAGE_URL, LAYOUT_ID, SHOW_OWN_BRAND, VALIDATION_STATUS, CAMPAIGN_USAGE_ID, STORE_END_DATE, PAGING_ALLOWED, CAROUSEL_BUTTON_TEXT_COLOR, CAROUSEL_BUTTON_BG_COLOR, CAROUSEL_BUTTON1_LABEL, CAROUSEL_BUTTON1_URL, CAROUSEL_BUTTON2_LABEL, CAROUSEL_BUTTON2_URL, CAROUSEL_HTML_OVERLAY, MOBILE_APP_TEASER_URL, CAROUSEL_CLAIM_URL, CAROUSEL_HERO_URL, CAROUSEL_BOX_COLOR, AVOID_CAMPAIGN_NAV_TEASER, CAROUSEL_BUTTON1_NEW_TAB, CAROUSEL_BUTTON2_NEW_TAB, SALE_QUALIFICATION_ID, SALE_TARGET_CAMPAIGN)
VALUES (CAMPAIGN_SEQ.nextval, 1, 'P', 0, 'A', to_date('2016-11-09', 'YYYY-MM-DD'), to_date('2116-11-09', 'YYYY-MM-DD'), to_date('2016-11-09', 'YYYY-MM-DD'), to_date('2018-07-02', 'YYYY-MM-DD'), null, null, null, 0, null, '4_COL_LEFT_NAV', 1, null, null, null, 1, null, null, null, null, null, null, null, null, null, null, null, 0, 0, 0, null, 0);
Or, use SELECT/UNION ALL:
INSERT INTO CAMPAIGN (CAMPAIGN_ID, SHOP_ID, CAMPAIGN_TYPE, SORT_ORDER, STATUS, VALID_FROM, VALID_TILL, CREATED_AT, MODIFIED_AT, CUSTOM_GRID_LAYOUT_CSS, IMAGE_URL, KEY, SHOW_PRODUCTS_FILTER, MOBILE_APP_IMAGE_URL, LAYOUT_ID, SHOW_OWN_BRAND, VALIDATION_STATUS, CAMPAIGN_USAGE_ID, STORE_END_DATE, PAGING_ALLOWED, CAROUSEL_BUTTON_TEXT_COLOR, CAROUSEL_BUTTON_BG_COLOR, CAROUSEL_BUTTON1_LABEL, CAROUSEL_BUTTON1_URL, CAROUSEL_BUTTON2_LABEL, CAROUSEL_BUTTON2_URL, CAROUSEL_HTML_OVERLAY, MOBILE_APP_TEASER_URL, CAROUSEL_CLAIM_URL, CAROUSEL_HERO_URL, CAROUSEL_BOX_COLOR, AVOID_CAMPAIGN_NAV_TEASER, CAROUSEL_BUTTON1_NEW_TAB, CAROUSEL_BUTTON2_NEW_TAB, SALE_QUALIFICATION_ID, SALE_TARGET_CAMPAIGN)
SELECT CAMPAIGN_SEQ.nextval, 1, 'C', 0, 'A', to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2116-11-23', 'YYYY-MM-DD'), to_date('2016-11-23', 'YYYY-MM-DD'), to_date('2018-07-02', 'YYYY-MM-DD'), null, null, null, 1, null, '5_COL', 0, null, 4, to_date('2116-11-23', 'YYYY-MM-DD'), 0, null, null, 'Artikel ab Mo., 02.12.', 'https://www.lidl.de', null, null, null, null, null, null, null, 0, 0, 0, null, 0
FROM dual
UNION ALL
SELECT CAMPAIGN_SEQ.nextval, 1, 'P', 0, 'A', to_date('2016-11-09', 'YYYY-MM-DD'), to_date('2116-11-09', 'YYYY-MM-DD'), to_date('2016-11-09', 'YYYY-MM-DD'), to_date('2018-07-02', 'YYYY-MM-DD'), null, null, null, 0, null, '4_COL_LEFT_NAV', 1, null, null, null, 1, null, null, null, null, null, null, null, null, null, null, null, 0, 0, 0, null, 0
FROM dual;

SQL Query joining 5 tables

Trying to create a query to select all jobs that are unpaid and who the customer is for that job.
So the is required to first work out a calculation of what they owe (by a sum of s_partorders qty x price found in s_parts) and then minus what they have paid from s_payments.
This query joins it all together but I don't know how to group it by jobNumber because there can be multiple payments and multiple part orders.
SELECT a.jobNumber, a.customerID, a.quoteStatus, a.costDelivery, a.costCallout, a.costLabour, b.customerID, b.firstName, b.lastName, c.paymentID, c.jobNumber, c.amount, d.orderID, d.jobNumber, d.partID, d.quantity, e.partID, e.sellPrice
FROM s_jobcards a
INNER JOIN s_customers b ON a.customerID = b.customerID
INNER JOIN s_payments c ON a.jobNumber = c.jobNumber
INNER JOIN s_partOrders d ON a.jobNumber = d.jobNumber
INNER JOIN s_parts e ON d.partID = e.partID
WHERE a.quoteStatus = 0
Sorry it's quite messy and incomplete...
Included table structure and some test data.
CREATE TABLE IF NOT EXISTS `s_customers` (
`customerID` int(20) NOT NULL AUTO_INCREMENT,
`firstName` text NOT NULL,
`lastName` text NOT NULL,
`address` text NOT NULL,
`suburb` text NOT NULL,
`state` text NOT NULL,
`postcode` text NOT NULL,
`phone` text NOT NULL,
`altPhone` text NOT NULL,
`email` text NOT NULL,
`notes` text NOT NULL,
`postAddress` text NOT NULL,
`serviceDueDate` date NOT NULL,
PRIMARY KEY (`customerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `s_customers` (`customerID`, `firstName`, `lastName`, `address`, `suburb`, `state`, `postcode`, `phone`, `altPhone`, `email`, `notes`, `postAddress`, `serviceDueDate`) VALUES
(1, 'David', 'Davinci', '654 Fake Road', 'Canning Vale', 'WA', '6164', '9546446', '45645646', 'dave#website.com', 'This guy is a butt', 'Cockburn Central', '2014-12-24'),
(2, 'Timmy', 'Trumpet', '69 something Street', 'Cockburn Central', 'WA', '6164', '9456456', '92344643', 'timmy#trumpet.com', 'Timmah?', '45 Timmy Street', '0000-00-00'),
(3, 'Jerry', 'Tester', '', '', '', '', '', '', '', '', '', '0000-00-00');
CREATE TABLE IF NOT EXISTS `s_jobcards` (
`jobNumber` int(6) NOT NULL AUTO_INCREMENT,
`dateReceived` date NOT NULL,
`workRequired` text NOT NULL,
`workCompleted` text NOT NULL,
`dateCompleted` date NOT NULL,
`customerID` int(5) NOT NULL,
`serviceTime` int(5) NOT NULL,
`serviceTech` int(1) NOT NULL,
`workOutstanding` text NOT NULL,
`quoteStatus` tinyint(1) NOT NULL DEFAULT '1',
`costDelivery` double NOT NULL,
`costCallout` double NOT NULL,
`costLabour` double NOT NULL,
PRIMARY KEY (`jobNumber`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `s_jobcards` (`jobNumber`, `dateReceived`, `workRequired`, `workCompleted`, `dateCompleted`, `customerID`, `serviceTime`, `serviceTech`, `workOutstanding`, `quoteStatus`, `costDelivery`, `costCallout`, `costLabour`) VALUES
(1, '2013-11-18', 'Create new service software. Yeah! 4534', 'Not a whole lot yet.?', '0000-00-00', 1, 5, 2, 'Complete this software?', 0, 50, 90, 90),
(2, '2013-11-18', 'work required', 'work done!', '0000-00-00', 1, 1, 3, 'work outstanding', 0, 0, 0, 0),
(3, '2014-12-01', 'Work harder.23432432 gdf', 'Go go!', '2014-12-01', 2, 1, 3, '', 1, 0, 0, 0),
(4, '0000-00-00', 'Whack some moles.', '', '0000-00-00', 3, 0, 1, '', 1, 0, 0, 0),
(5, '0000-00-00', '', '', '0000-00-00', 1, 0, 0, '', 1, 0, 0, 0);
CREATE TABLE IF NOT EXISTS `s_partOrders` (
`orderID` int(11) NOT NULL AUTO_INCREMENT,
`jobNumber` int(11) NOT NULL,
`partID` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`orderID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `s_partOrders` (`orderID`, `jobNumber`, `partID`, `quantity`) VALUES
(2, 0, 1, 5),
(3, 1, 1, 2),
(4, 1, 1, 6);
CREATE TABLE IF NOT EXISTS `s_parts` (
`partID` int(10) NOT NULL AUTO_INCREMENT,
`partNumber` varchar(50) NOT NULL,
`partDescription` text NOT NULL,
`modelID` int(5) NOT NULL,
`buyPrice` double NOT NULL,
`sellPrice` double NOT NULL,
`notes` text NOT NULL,
PRIMARY KEY (`partID`),
UNIQUE KEY `partNumber` (`partNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `s_parts` (`partID`, `partNumber`, `partDescription`, `modelID`, `buyPrice`, `sellPrice`, `notes`) VALUES
(1, '3453453453', 'Test Part', 1, 10.02, 30.5, 'This is a test part.');
CREATE TABLE IF NOT EXISTS `s_payments` (
`paymentID` int(11) NOT NULL AUTO_INCREMENT,
`amount` double NOT NULL,
`type` text NOT NULL,
`jobNumber` int(11) NOT NULL,
`paymentDate` date NOT NULL,
PRIMARY KEY (`paymentID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `s_payments` (`paymentID`, `amount`, `type`, `jobNumber`, `paymentDate`) VALUES
(2, 200, 'Visa', 1, '2014-12-05'),
(3, 20, 'Visa', 1, '2014-12-05');
Use outer joins where there might be no matching records, and aggregating data to jobnumber before joining will assist in ensuring the numbers are accurate:
select
j.jobNumber, j.customerID, j.quoteStatus, j.costDelivery, j.costCallout, j.costLabour
, c.customerID, c.firstName, c.lastName
, p.parts_sellprice
, sum(jp.amount) as paid
from s_jobcards as j
inner join s_customers as c on j.customerID = c.customerID
left outer join s_payments as jp on j.jobNumber = jp.jobNumber
left outer join (
select
d.jobNumber, sum(d.quantity * e.sellPrice) parts_sellprice
from s_partOrders d
left outer join s_parts e ON d.partID = e.partID
group by
d.jobNumber
) as p on j.jobNumber = p.jobNumber
group by
j.jobNumber, j.customerID, j.quoteStatus, j.costDelivery, j.costCallout, j.costLabour
, c.customerID, c.firstName, c.lastName
;
nb: I have assumed the sell price is multiplied by quantity
see this sqlfiddle demo: http://sqlfiddle.com/#!2/96f4c/1
select
j.jobNumber, j.customerID, j.quoteStatus, j.costDelivery, j.costCallout, j.costLabour
, c.customerID, c.firstName, c.lastName
, p.parts_sellprice
, sum(jp.amount) as paid
, (j.costDelivery + j.costCallout + j.costLabour + p.parts_sellprice) as Total_Cost
, (j.costDelivery + j.costCallout + j.costLabour + p.parts_sellprice) - sum(jp.amount) as Amount_Outstanding
from s_jobcards as j
inner join s_customers as c on j.customerID = c.customerID
left outer join s_payments as jp on j.jobNumber = jp.jobNumber
left outer join (
select
d.jobNumber, sum(d.quantity * e.sellPrice) parts_sellprice
from s_partOrders d
left outer join s_parts e ON d.partID = e.partID
group by
d.jobNumber
) as p on j.jobNumber = p.jobNumber
group by
j.jobNumber, j.customerID, j.quoteStatus, j.costDelivery, j.costCallout, j.costLabour
, c.customerID, c.firstName, c.lastName
;

How do I write this MySQL query to get the correct information? (Subquery, multiple subqueries)

Here is the query that I am working on:
SELECT `unitid`, `name` FROM apartmentunits
WHERE aptid = (
SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 1 AND condnum = 1
)
What I am having trouble figuring out is how to write this to add more rentcondition limiters to filter this list down more.
SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 1 AND condnum = 1
Data:
CREATE TABLE IF NOT EXISTS `rentconditionsmap` (
`rcid` bigint(10) unsigned NOT NULL AUTO_INCREMENT,
`rentcondid` int(3) unsigned NOT NULL,
`condnum` tinyint(3) unsigned NOT NULL,
`aptid` bigint(10) unsigned DEFAULT NULL,
PRIMARY KEY (`rcid`), KEY `aptid` (`aptid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;
INSERT INTO `rentconditionsmap`
(`rcid`, `rentcondid`, `condnum`, `aptid`)
VALUES
(1, 1, 1, 1),
(2, 2, 1, 1),
(3, 3, 0, 1),
(4, 4, 1, 1),
(5, 8, 0, 1);
CREATE TABLE IF NOT EXISTS `apartmentunits` (
`unitid` bigint(10) NOT NULL AUTO_INCREMENT,
`aptid` bigint(10) NOT NULL,
`name` varchar(6) NOT NULL,
`verified` tinyint(1) NOT NULL DEFAULT '0',
`rentcost` int(4) unsigned DEFAULT NULL,
`forrent` tinyint(1) NOT NULL DEFAULT '0',
`unittypekey` varchar(2) DEFAULT NULL,
`sqft` smallint(6) DEFAULT NULL,
PRIMARY KEY (`unitid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=121 ;
INSERT INTO `apartmentunits`
(`unitid`, `aptid`, `name`, `verified`, `rentcost`, `forrent`, `unittypekey`, `sqft`)
VALUES
(1, 1, '3', 1, 540, 0, '2B', NULL),
(2, 1, '5', 1, NULL, 0, '2B', NULL),
(3, 1, '7', 1, NULL, 0, '2B', NULL),
(53, 1, '1', 1, NULL, 0, '2B', NULL),
(54, 1, '2', 1, NULL, 0, '2B', NULL),
(55, 1, '4', 1, 570, 0, '2B', NULL),
(56, 1, '6', 1, NULL, 0, '2B', NULL),
(57, 1, '8', 1, NULL, 0, '2B', NULL),
(58, 1, '9', 1, NULL, 0, '2B', NULL),
(59, 1, '10', 1, NULL, 0, '2B', NULL),
(60, 1, '11', 1, NULL, 0, '2B', NULL);
As Eric J said as a comment:
Try changing = to IN
SELECT `unitid`, `name` FROM apartmentunits
WHERE `aptid` IN (
SELECT `aptid` FROM rentconditionsmap WHERE rentcondid = 1 AND condnum = 1
)
why not:
SELECT unitid, name
FROM apartmentunits a
INNER JOIN rentconditionsmap r on a.aptid = r.aptid
WHERE (rentcondid = 1 and condnum = 1) OR (rentcondid = 2 and condnum = 2)
Using ANSI-92 join syntax:
SELECT au.unitid,
au.name
FROM APARTMENTUNITS au
JOIN RENTCONDITIONSMAP rcm ON rcm.aptid = au.aptid
AND rcm.rentcondid = 1
AND rcm.condnum = 1
Use a JOIN (below is TSQL sintax for a join, or you can use the explicit INNER JOIN).
SELECT apartmentunits.unitid, apartmentunits.name
FROM apartmentunits, rentconditionsmap
WHERE apartmentunits.aptid = rentconditionsmap.aptid
AND rentconditionsmap.rentcondid = 1
AND rentconditionsmap.condnum = 1
-- AND whatever else...