DB-Fiddle
CREATE TABLE logistics (
id int primary key,
campaign VARCHAR(255),
event_type VARCHAR (255),
date_offered VARCHAR (255),
date_ordered VARCHAR (255),
date_delivered VARCHAR (255),
date_recorded VARCHAR (255),
date_completed VARCHAR (255),
quantity_offered VARCHAR(255),
quantity_ordered VARCHAR(255),
quantity_delivered VARCHAR(255),
quantity_recorded VARCHAR(255),
quantity_completed VARCHAR(255)
);
INSERT INTO logistics
(id, campaign, event_type,
date_offered, date_ordered,
date_delivered, date_recorded, date_completed,
quantity_offered, quantity_ordered,
quantity_delivered, quantity_recorded, quantity_completed
)
VALUES
("1", "C001", "offered", "2019-04-10", NULL, NULL, NULL, NULL, "500", NULL, NULL, NULL, NULL),
("2", "C001", "ordered", NULL, "2019-04-16", NULL, NULL, NULL, NULL, "450", NULL, NULL, NULL),
("3", "C001", "stored", NULL, NULL, "2019-04-18", NULL, NULL, NULL, NULL, "465", NULL, NULL),
("4", "C001", "stored", NULL, NULL, NULL, "2019-04-20", NULL, NULL, NULL, NULL, "440", NULL),
("5", "C001", "stored", NULL, NULL, NULL, NULL, "2019-04-22", NULL, NULL, NULL, NULL, "445"),
("6", "C002", "offered", "2019-08-15", NULL, NULL, NULL, NULL, "600", NULL, NULL, NULL, NULL),
("7", "C002", "ordered", NULL, "2019-09-03", NULL, NULL, NULL, NULL, "700", NULL, NULL, NULL),
("8", "C002", "stored", NULL, NULL, "2019-09-05", NULL, NULL, NULL, NULL, "690", NULL, NULL),
("9", "C002", "stored", NULL, NULL, NULL, "2019-09-08", NULL, NULL, NULL, NULL, "692", NULL),
("10", "C003", "offered", "2019-10-24", NULL, NULL, NULL, NULL, "300", NULL, NULL, NULL, NULL),
("11", "C003", "ordered", NULL, "2019-10-28", NULL, NULL, NULL, NULL, "250", NULL, NULL, NULL),
("12", "C003", "stored", NULL, NULL, "2019-10-31", NULL, NULL, NULL, NULL, "320", NULL, NULL),
("13", "C004", "offered", "2019-11-05", NULL, NULL, NULL, NULL, "800", NULL, NULL, NULL, NULL),
("14", "C004", "ordered", NULL, "2019-11-14", NULL, NULL, NULL, NULL, "870", NULL, NULL, NULL),
("15", "C004", "stored", NULL, NULL, "2019-11-16", NULL, NULL, NULL, NULL, "740", NULL, NULL),
("16", "C005", "offered", "2019-12-17", NULL, NULL, NULL, NULL, "240", NULL, NULL, NULL, NULL),
("17", "C005", "ordered", NULL, "2020-01-12", NULL, NULL, NULL, NULL, "250", NULL, NULL, NULL),
("18", "C005", "stored", NULL, NULL, "2020-01-16", NULL, NULL, NULL, NULL, "226", NULL, NULL),
("19", "C006", "offered", "2020-01-09", NULL, NULL, NULL, NULL, "100", NULL, NULL, NULL, NULL),
("20", "C006", "ordered", NULL, "2020-01-23", NULL, NULL, NULL, NULL, "105", NULL, NULL, NULL),
("21", "C007", "offered", "2020-02-17", NULL, NULL, NULL, NULL, "900", NULL, NULL, NULL, NULL),
("22", "C008", "offered", "2020-02-25", NULL, NULL, NULL, NULL, "400", NULL, NULL, NULL, NULL);
The table above displays the purchasing process of different campaigns.
The first three process steps are defined by the event_types offered, ordered and stored.
Once a campaign has reached the process step stored the process continues with different dates called date_completed, date_recorded and date_delivered. Basically, those dates are sub_events from the event_type stored.
The hierarchy of those events is like this:
event_type = stored > ordered > offered
date = date_completed > date_recorded > date_delivered
Now, I want to extract the campaigns based on their highest event_type or - in case they already have reached the event_type stored - based on their highest date according to the defined hierarchy. The result should look like this:
campaign event_type date quantity
C001 stored 2019-04-22 445
C002 stored 2019-09-08 692
C003 stored 2019-10-31 320
C004 stored 2019-11-16 740
C005 stored 2020-01-16 226
C006 ordered 2020-01-23 105
C007 offered 2020-02-17 900
C008 offered 2020-02-25 400
With reference to this question I tried to modify the query like this:
SELECT
campaign,
event_type,
coalesce(date_offered, date_ordered) as main_event_date,
coalesce(date_delivered, date_recorded, date_completed) as sub_event_date,
coalesce(quantity_offered, quantity_ordered) as main_event_quantity,
coalesce(quantity_delivered, quantity_recorded, quantity_completed) as sub_event_quantity
FROM logistics lg
WHERE lg.id = (SELECT lg2.id
FROM logistics lg2
WHERE lg2.campaign = lg.campaign
ORDER BY field(lg2.event_type, 'stored', 'ordered', 'offered')
field(lg2.sub_event_date, 'date_completed', 'date_recorded', 'date_delivered')
LIMIT 1
);
However, I don't know how I should you use the field function once the campaign is in the event_type stored because there is no sub_event column for the dates?
You can use a subquery and group te data by campaign:
SELECT campaign,MAX(event_type) AS event_type,
CASE WHEN MAX(sub_event_date)>MAX(main_event_date) THEN MAX(sub_event_date) ELSE MAX(main_event_date) END AS event_date,
CASE WHEN MAX(sub_event_date)>MAX(main_event_date) THEN MAX(sub_event_quantity) ELSE MAX(main_event_quantity) END AS event_quantity
FROM (
SELECT
campaign,
event_type,
coalesce(date_offered, date_ordered) as main_event_date,
coalesce(date_delivered, date_recorded, date_completed) as sub_event_date,
coalesce(quantity_offered, quantity_ordered) as main_event_quantity,
coalesce(quantity_delivered, quantity_recorded, quantity_completed) as sub_event_quantity
FROM logistics lg) l
GROUP BY campaign
DB-Fiddle
The solution is as the following:
Step 1: Create an aggregated_sub_table called AGR_logistics which adds an additional column called sub_event_type to the original table:
CREATE TABLE AGR_logistics
SELECT
id,
campaign,
event_type,
(CASE
WHEN event_type = "stored" AND quantity_delivered IS NOT NULL THEN "delivered"
WHEN event_type = "stored" AND quantity_recorded IS NOT NULL THEN "recorded"
WHEN event_type = "stored" AND quantity_completed IS NOT NULL THEN "completed"
ELSE NULL END) AS sub_event_type,
date_offered,
date_ordered,
date_delivered,
date_recorded,
date_completed,
quantity_offered,
quantity_ordered,
quantity_delivered,
quantity_recorded,
quantity_completed
FROM logistics;
Step 2: Run a correleated subquery as described here over AGR_logistics:
SELECT
id,
campaign,
event_type,
sub_event_type,
coalesce(date_offered, date_ordered, date_delivered, date_recorded, date_completed) as event_date,
coalesce(quantity_offered, quantity_ordered, quantity_delivered, quantity_recorded, quantity_completed) as event_quantity
FROM AGR_logistics AGR_01
WHERE AGR_01.id = (SELECT AGR_02.id
FROM AGR_logistics AGR_02
WHERE AGR_02.campaign = AGR_01.campaign
ORDER BY
field(AGR_02.event_type, 'stored', 'ordered', 'offered'),
field(AGR_02.sub_event_type, 'completed', 'recorded', 'delivered')
LIMIT 1
);
Related
I am trying to update a Stored JSON in my database and i am unable to run the following update query. I have copied below a select statement and an update statement
SELECT
`core_animal_event`. `animal_id` AS `MilkingEvent_animalID`,
JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."62"')) AS `MilkingEvent_milkCompositeLitres`,
coalesce(JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."68"')) +
JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."61"')) +
JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."59"')))
FROM `core_animal_event` WHERE (`core_animal_event`. `event_type` = 2) AND (`core_animal_event`. `country_id` = '10');
UPDATE `core_animal`
SET
JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."62"')) =
coalesce(JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."68"')) +
JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."61"')) +
JSON_UNQUOTE(JSON_EXTRACT(`core_animal_event`.`additional_attributes`, '$."59"')))
WHERE (`core_animal_event`. `event_type` = 2) AND (`core_animal_event`. `country_id` = '10')
The following is the sample data from which we have a stored JSON column called additional_attribute and animal_id which is unique
# animal_id, additional_attributes
'2576', '{\"59\": null, \"61\": null, \"62\": null, \"63\": null, \"64\": null, \"65\": null, \"66\": null, \"67\": null, \"68\": null, \"69\": \"1\", \"70\": \"2\", \"71\": \"1\", \"72\": null, \"73\": \"2\", \"74\": \"1\", \"75\": null, \"76\": null, \"77\": [\"1\"], \"78\": \"32\", \"79\": \"70\", \"80\": \"4\", \"81\": null, \"82\": null, \"83\": null, \"84\": \"Mkiwa\", \"85\": \"19280\", \"86\": \"2405\", \"87\": \"TNZ000192802405\", \"88\": \"Brownwhite\", \"89\": \"1565789020239.jpg\", \"90\": \"1565789049469.jpg\", \"96\": null, \"97\": null, \"98\": null, \"99\": \"1\", \"100\": null, \"101\": null, \"102\": null, \"103\": null, \"104\": null, \"105\": null, \"106\": null, \"107\": null, \"108\": null, \"109\": null, \"110\": null, \"111\": null, \"112\": null, \"113\": null, \"114\": null, \"115\": null, \"116\": null, \"117\": null, \"118\": null, \"119\": null, \"120\": null, \"121\": null, \"122\": null, \"123\": null, \"124\": null, \"125\": null, \"126\": null, \"127\": null, \"128\": null, \"129\": null, \"130\": null, \"131\": null, \"132\": null, \"133\": null, \"134\": null, \"135\": null, \"136\": null, \"137\": null, \"138\": null, \"139\": null, \"141\": null, \"142\": null, \"143\": null, \"144\": null, \"145\": null}'
The following is an example of a create statement
CREATE TABLE `core_animal_event` (
`id` int NOT NULL AUTO_INCREMENT,
`animal_id` int NOT NULL,
`event_type` int NOT NULL,
`additional_attributes` json DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `org_id` (`country_id`),
KEY `animal_id` (`animal_id`),
KEY `event_type` (`event_type`),
CONSTRAINT `core_animal_event_ibfk_1` FOREIGN KEY (`animal_id`) REFERENCES `core_animal` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=941817 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT;
Escape characters are not necessary here. I even think they may be the source of the problem.
Here's my code for the tests :
CREATE TABLE `core_animal_event` (
`animal_id` int(11) NOT NULL AUTO_INCREMENT,
`additional_attributes` json DEFAULT NULL,
`event_type` int(11) NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`animal_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
INSERT INTO core_animal_event
(animal_id, additional_attributes, event_type, country_id)
VALUES(1, '{ "59": null, "61": null, "62": null, "63": null, "64": null, "65": null, "66": null, "67": null, "68": null, "69": "1", "70": "2", "71": "1", "72": null, "73": "2", "74": "1", "75": null, "76": null, "77": ["1"], "78": "32", "79": "70", "80": "4", "81": null, "82": null, "83": null, "84": "Mkiwa", "85": "19280", "86": "2405", "87": "TNZ000192802405", "88": "Brownwhite", "89": "1565789020239.jpg", "90": "1565789049469.jpg", "96": null, "97": null, "98": null, "99": "1", "100": null, "101": null, "102": null, "103": null, "104": null, "105": null, "106": null, "107": null, "108": null, "109": null, "110": null, "111": null, "112": null, "113": null, "114": null, "115": null, "116": null, "117": null, "118": null, "119": null, "120": null, "121": null, "122": null, "123": null, "124": null, "125": null, "126": null, "127": null, "128": null, "129": null, "130": null, "131": null, "132": null, "133": null, "134": null, "135": null, "136": null, "137": null, "138": null, "139": null, "141": null, "142": null, "143": null, "144": null, "145": null}', 2, 10);
Without escape characters \, your SELECT query work.
For your update, here's an example :
UPDATE core_animal_event
SET additional_attributes = json_set(additional_attributes, '$."62"',
COALESCE(JSON_UNQUOTE(JSON_EXTRACT(additional_attributes, '$."68"')) +
JSON_UNQUOTE(JSON_EXTRACT(additional_attributes, '$."61"')) +
JSON_UNQUOTE(JSON_EXTRACT(additional_attributes, '$."59"')))
)
WHERE (event_type = 2) AND (country_id = '10');
//-------
EDIT:
Be careful when using JSON_EXTRACT and COALESCE function, in case all values are null, the returned value is 0, not a null value.
EDIT 2:
Akina is right, your COALESCE function is no good... As you do, it's an addition (but maybe that's what you want...)
EDIT 3:
If you want to use COALESCE here's an example:
SELECT animal_id AS colID, JSON_UNQUOTE(JSON_EXTRACT(additional_attributes, '$."62"')) AS col62,
COALESCE (
IF(JSON_TYPE(JSON_EXTRACT(additional_attributes, '$."68"'))='NULL', null, JSON_EXTRACT(additional_attributes, '$."68"')),
IF(JSON_TYPE(JSON_EXTRACT(additional_attributes, '$."59"'))='NULL', null, JSON_EXTRACT(additional_attributes, '$."59"')),
IF(JSON_TYPE(JSON_EXTRACT(additional_attributes, '$."61"'))='NULL', null, JSON_EXTRACT(additional_attributes, '$."61"'))
) AS result_of_coalesce
FROM core_animal_event WHERE (event_type = 2) AND (country_id = '10');
I am getting this error
InsertRecord(InsertRow): HResult of -2147217873 (80040e2f)
Error Source: Microsoft OLE DB Provider for SQL Server Error
Description : The INSERT statement conflicted with the CHECK constraint CK_ContactName. The conflict occurred in database EPIC.7.5_GR_SM_ETLTRAINING; table dbo.ContactName.
The Statements
CREATE TABLE [dbo].[ContactName](
[UniqContactName] [dbo].[DM_UNIQID] IDENTITY(65536,1) NOT NULL,
[UniqFixedContactName] [dbo].[DM_UNIQID] NOT NULL,
[UniqEntity] [dbo].[DM_UNIQID] NOT NULL,
[LkPrefix] [dbo].[DM_PREFIX] NOT NULL,
[FullName] [dbo].[DM_NAME] NOT NULL,
[FirstName] [varchar](30) NOT NULL,
[MiddleName] [varchar](16) NOT NULL,
[LastName] [varchar](30) NOT NULL,
[LkSuffix] [dbo].[DM_SUFFIX] NOT NULL,
[DescriptionOf] [dbo].[DM_DESC_050] NOT NULL,
[Title] [dbo].[DM_TITLE] NOT NULL,
[Department] [dbo].[DM_DEPARTMENT] NOT NULL,
[UniqContactAddressMain] [dbo].[DM_UNIQID] NOT NULL,
[UniqContactAddressEmployer] [dbo].[DM_UNIQID] NOT NULL,
[UniqContactNumberMain] [dbo].[DM_UNIQID] NOT NULL,
[UniqContactNumberEmailMain] [dbo].[DM_UNIQID] NOT NULL,
[ContactMethodCode] [char](1) NOT NULL,
[InformalHeading] [varchar](50) NOT NULL,
[FormalHeading] [varchar](50) NOT NULL,
[BirthDate] [dbo].[DM_DATE] NULL,
[GenderCode] [char](1) NOT NULL,
[SSN] [char](9) NOT NULL,
[MaritalStatusCode] [char](1) NOT NULL,
[RelationToInsuredCode] [char](2) NOT NULL,
[LkLanguage] [dbo].[DM_LANGUAGE] NOT NULL,
[Comments] [dbo].[DM_COMMENT] NOT NULL,
[BillingDeliveryCode] [char](1) NOT NULL,
[ServicingDeliveryCode] [char](1) NOT NULL,
[MarketingDeliveryCode] [char](1) NOT NULL,
[CategoryCode] [char](1) NOT NULL,
[EmployerName] [dbo].[DM_NAME] NOT NULL,
[LkOccupation] [dbo].[DM_OCCUPATION] NOT NULL,
[HiredDate] [dbo].[DM_DATE] NULL,
[YearsEmployed] [smallint] NULL,
[YearsPriorEmployer] [smallint] NULL,
[FEIN] [char](9) NOT NULL,
[DUNSNumber] [char](9) NOT NULL,
[CdNAICSCode] [char](6) NOT NULL,
[CdSICCode] [char](8) NOT NULL,
[BusinessTypeCode] [char](2) NOT NULL,
[BusinessTypeOtherDesc] [varchar](50) NOT NULL,
[NumberEmployees] [smallint] NULL,
[NumberMembersManagers] [int] NULL,
[BusinessStartedDate] [datetime] NULL,
[NatureOfBusinessCode] [char](2) NOT NULL,
[NatureOfBusinessOtherDesc] [varchar](50) NOT NULL,
[CreditBureauNameCode] [char](5) NOT NULL,
[CreditBureauNameOtherDesc] [varchar](50) NOT NULL,
[CreditBureauIDNumber] [varchar](30) NOT NULL,
[DriverLicenseNumber] [varchar](25) NOT NULL,
[LicensedState] [char](4) NOT NULL,
[LicensedDate] [datetime] NULL,
[LicensedMADate] [dbo].[DM_DATE] NULL,
[DriverTypeCode] [char](1) NOT NULL,
[GoodStudentCode] [char](1) NOT NULL,
[DriverTrainingCode] [char](1) NOT NULL,
[AccidentPreventionCourseDate] [dbo].[DM_DATE] NULL,
[CommercialExperienceBeganDate] [dbo].[DM_DATE] NULL,
[MatchClientNameOf] [smallint] NOT NULL,
[InsertedByCode] [dbo].[DM_INSERTUPDATEBYCODE] NOT NULL,
[InsertedDate] [dbo].[DM_DATETIME] NOT NULL,
[UpdatedByCode] [dbo].[DM_INSERTUPDATEBYCODE] NOT NULL,
[UpdatedDate] [dbo].[DM_DATETIME] NULL,
[Flags] [dbo].[DM_FLAGS] NOT NULL,
[ts] [datetime] NOT NULL,
[SIN] [char](9) NOT NULL,
[BusinessNumber] [varchar](30) NOT NULL,
[BusinessIDNumber] [varchar](30) NOT NULL,
[IBCCode] [char](6) NOT NULL,
CONSTRAINT [PK_ContactName] PRIMARY KEY NONCLUSTERED ALTER TABLE [dbo].[ContactName]
WITH CHECK ADD CONSTRAINT [CK_ContactName]
CHECK ((
[UniqContactName]=(-1)
AND [UniqEntity]=(-1)
OR [UniqContactName]>(-1)
AND [UniqEntity]>(-1)
))
GO
I have checked contactName db and all the rows from uniqueContactName all have a value above 65000, then for UniqEntity they all are above 65000 as well.
Does anyone have an idea why this would fail?
I am trying to implement this atomic transaction in django and am following this example from the docs. But changes are found to persist despite rollback. I've searched for similar questions and most common cause seems to be catching integrity error inside atomic block, but I am not doing that.
Following is my django code:
def get_lead_alert_data(params):
with transaction.atomic():
with acquire_lead_lock():
caller = params['caller']
via = params['via']
called = params['called']
leadphone = LeadsPhone.objects.filter(phone_number=caller, brokerage__isnull=True).first()
if leadphone:
lead_id = leadphone.lead_id
else:
lead_id = create_lead_from_inbound_call(caller, called)
created, requirement = get_or_create_requirement_from_inbound_call(via, lead_id)
picking_agent = Users.objects.get(phone_mobile=called)
if created:
RequirementAssignment.objects.create(requirement=requirement, agent=picking_agent)
assigned_to = picking_agent.user_name
else:
assigned_requirement = RequirementAssignment.objects.filter(brokerage__active=True,
requirement=requirement).first() #There will be only one such requirement
if not assigned_requirement.agent:
assigned_requirement.agent = picking_agent
assigned_requirement.save()
assigned_to = assigned_requirement.agent.user_name if assigned_requirement else 'nobody'
return {'lead_id': lead_id, 'assigned_to': assigned_to, 'picking_by': picking_agent.user_name}
I also checked resulting logs in mysql and it is indeed calling a rollback, yet the changes persist.
3043 Connect root#localhost on reserve_db_2
3043 Query SET NAMES utf8
3043 Query set autocommit=0
3043 Query set autocommit=1
3043 Query SET SQL_AUTO_IS_NULL = 0
3043 Query set autocommit=0
3043 Query lock table person write, leads write, leads_phones write, leads_emails write, requirements write, tele_phones read
3043 Query SELECT `leads_phones`.`id`, `leads_phones`.`lead_id`, `leads_phones`.`phone_number`, `leads_phones`.`brokerage_id`, `leads_phones`.`created` FROM `leads_phones` WHERE (`leads_phones`.`phone_number` = '9899696089' AND `leads_phones`.`brokerage_id` IS NULL) ORDER BY `leads_phones`.`id` ASC LIMIT 1
3043 Query INSERT INTO `person` (`user_id`, `fullname`, `mobile_no`, `fb_location`, `fb_email`, `fb_aboutme`, `fb_avatar`, `goog_email`, `goog_avatar`, `uploaded_avatar`, `first_name`, `last_name`, `description`, `address`, `is_admin`, `reviewer_badge`, `title`, `phone_home`, `phone_work`, `phone_other`, `phone_fax`, `status`, `address_street`, `address_city`, `address_region_id`, `address_country`, `address_postalcode`, `created`, `last_updated`, `created_by`, `modified_by`, `deleted`) VALUES (NULL, '', NULL, '', '', '', '', '', '', '', '', '', '', '', NULL, '1ST TIME REVIEWER', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2014-09-06 11:12:03', '2014-09-06 11:12:03', '', NULL, 0)
140906 16:40:05 3043 Query INSERT INTO `leads` (`id`, `date_entered`, `date_modified`, `modified_user_id`, `created_by`, `description`, `deleted`, `assigned_user_id`, `salutation`, `first_name`, `middle_name`, `last_name`, `title`, `department`, `do_not_call`, `primary_email_address`, `secondary_email_address`, `phone_home`, `phone_mobile`, `phone_work`, `phone_other`, `phone_fax`, `primary_address_street`, `primary_address_city`, `primary_address_state`, `primary_address_postalcode`, `primary_address_country`, `alt_address_street`, `alt_address_city`, `alt_address_state`, `alt_address_postalcode`, `alt_address_country`, `converted`, `refered_by`, `lead_source_description`, `status`, `status_description`, `reports_to_id`, `residence_phone`, `citizenship`, `primary_address_street_by_agent`, `office_location`, `owned_rented`, `owned_rented_by_agent`, `unique_id`, `reason_for_status_change`, `annual_income`, `annual_income_by_agent`, `designation`, `executive_level`, `executive_level_by_agent`, `present_company`, `website`, `lead_type_fav`, `lead_type_c`, `facebook_url`, `linkedin_url`, `twitter_url`, `google_plus_url`, `assigned_user_date`, `worked_by_tele`, `worked_by_sales`, `off_campaign_id`, `activity_done`, `activity_completed`, `queue_name`, `queue_description`, `history_notes`, `lead_category`, `trans_type`, `potential`, `referral_remark`, `referral_name`, `referral_no`, `referral_email`, `primary_secondary_lead`, `met_face_to_face`, `met_site_visit`, `met_final_negotiation`, `total_met`, `is_duplicate`, `is_duplicate_date`, `queue_abort_remark`, `referer_url`, `landing_url`, `leadpage_url`, `lead_projects`, `lead_projects_ids`, `lead_max_budget`, `lead_source`, `person_id`, `brokerage_id`, `lead_parent_id`) VALUES ('1440bb40-4f8a-4f87-917f-6aca0c758711', NULL, NULL, NULL, '', NULL, 0, '', NULL, NULL, NULL, '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', NULL, NULL, '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 315601, NULL, NULL)
3043 Query INSERT INTO `leads_phones` (`lead_id`, `phone_number`, `brokerage_id`, `created`) VALUES ('1440bb40-4f8a-4f87-917f-6aca0c758711', '9899696089', NULL, '2014-09-06 11:12:03')
3043 Query SELECT `tele_phones`.`id`, `tele_phones`.`source_id`, `tele_phones`.`project_id`, `tele_phones`.`locality_id`, `tele_phones`.`cluster_id`, `tele_phones`.`city_id` FROM `tele_phones` WHERE `tele_phones`.`id` = '3314892' LIMIT 21
3043 Query INSERT INTO `requirements` (`id`, `req_unique_id`, `lead_id`, `user_id`, `name`, `date_entered`, `date_modified`, `created_by`, `modified_user_id`, `assigned_user_id`, `deleted`, `req_type`, `category`, `bhk`, `unit_type`, `construction_phase`, `main_entrance_facing`, `balcony_facing`, `furnish_state`, `plc`, `locality`, `cluster`, `city`, `region`, `project`, `plot_area`, `super_area`, `price_sft_syd`, `price`, `total_price`, `cash_in_hand`, `need_loan`, `description`, `is_active_req`) VALUES ('63494d0d-88f8-44f5-816c-af4bb5ec439e', NULL, '1440bb40-4f8a-4f87-917f-6aca0c758711', NULL, '', NULL, NULL, '', '', '', NULL, '', '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, 1, 1, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, 1)
3043 Query unlock tables
3043 Query rollback
3043 Query set autocommit=1
Ohk, I checked out mysql docs. Looks like unlocking tables implicitly causes a commit if there are any locked tables, which there are in my case. Will have to find a workaround.
Fiddle Here:
http://sqlfiddle.com/#!2/2f85f4/1
I am trying to create an 'inventory demand' report essentially; what products were sold between X and Y and how much of them.
The closest I can get is this query, but this doesn't return the correct math.
Can someone please offer some guidance?
SELECT orders_products.op_products_name
, orders_products.op_products_id
, SUM(orders_products.op_products_qty) AS TotalSold
FROM orders_products
, orders
WHERE orders.orders_date_purchased
AND orders.orders_date_purchased BETWEEN '2012-11-05 00:00:00' AND '2012-11-10 00:00:00'
GROUP
BY orders_products.op_products_id
ORDER
BY TotalSold DESC
The schema is available here:
--
-- Table structure for table orders
CREATE TABLE IF NOT EXISTS orders (
orders_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
orders_date_purchased timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
orders_delivery_name varchar(100) NOT NULL,
orders_delivery_company_name varchar(100) NOT NULL,
orders_delivery_address varchar(255) NOT NULL,
orders_delivery_city varchar(100) NOT NULL,
orders_delivery_state char(2) NOT NULL,
orders_delivery_zipcode char(5) NOT NULL,
orders_delivery_phone char(10) NOT NULL,
orders_delivery_email varchar(100) NOT NULL,
orders_billing_name varchar(120) DEFAULT NULL,
orders_billing_address varchar(255) DEFAULT NULL,
orders_billing_city varchar(100) DEFAULT NULL,
orders_billing_state char(2) DEFAULT NULL,
orders_billing_zipcode char(5) DEFAULT NULL,
orders_billing_phone char(10) DEFAULT NULL,
orders_billing_email varchar(100) DEFAULT NULL,
orders_users_ID bigint(20) NOT NULL,
orders_distributor_ID bigint(20) DEFAULT NULL,
orders_affiliate_ID bigint(20) DEFAULT NULL,
orders_sales_tax decimal(11,2) NOT NULL,
orders_discount_applied decimal(11,2) DEFAULT NULL,
orders_ip_address char(15) NOT NULL,
orders_shipping_method varchar(255) NOT NULL,
orders_payment_method int(10) unsigned NOT NULL,
orders_order_total decimal(11,2) NOT NULL,
orders_shipping_cost decimal(11,2) DEFAULT NULL,
orders_total_saved decimal(11,2) NOT NULL,
orders_placed_by bigint(20) NOT NULL,
notes blob,
orders_inv_status int(11) DEFAULT NULL,
orders_date_modified timestamp NULL DEFAULT NULL,
orders_process_status int(11) DEFAULT '1',
PRIMARY KEY (orders_ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2379 ;
--
-- Dumping data for table orders
INSERT INTO orders (orders_ID, orders_date_purchased, orders_delivery_name, orders_delivery_company_name, orders_delivery_address, orders_delivery_city, orders_delivery_state, orders_delivery_zipcode, orders_delivery_phone, orders_delivery_email, orders_billing_name, orders_billing_address, orders_billing_city, orders_billing_state, orders_billing_zipcode, orders_billing_phone, orders_billing_email, orders_users_ID, orders_distributor_ID, orders_affiliate_ID, orders_sales_tax, orders_discount_applied, orders_ip_address, orders_shipping_method, orders_payment_method, orders_order_total, orders_shipping_cost, orders_total_saved, orders_placed_by, notes, orders_inv_status, orders_date_modified, orders_process_status) VALUES
(1, '2012-11-05 19:58:12', 'John Smith', '', '123 Manatee Street', 'Navarre', 'FL', '32566', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 83, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 61.59, 0.00, 0.00, 0, NULL, 8, NULL, 3),
(2, '2012-11-06 01:05:20', 'Judy Richards', '', '456 Devmor Ct', 'Navarre', 'FL', '32566', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 87, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 158.97, 0.00, 0.00, 0, NULL, 8, NULL, 3),
(4, '2012-11-08 04:32:23', 'John Smith', '', '123 Manatee Street', 'Navarre', 'FL', '32578', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 92, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 52.99, NULL, 0.00, 0, NULL, 8, '0000-00-00 00:00:00', 3),
(5, '2012-11-09 00:11:54', 'Adam Davis', '', '4307 D134 Legendary Dr.', 'Navarre', 'FL', '32541', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 89, 84, 0, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 160.51, 0.00, 0.00, 0, NULL, 8, NULL, 3),
(6, '2012-11-09 21:14:25', 'Judy Sterling', '', '2310 Lexington Lane', 'Navarre', 'FL', '32566', '8508675309', 'email#email.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 87, NULL, NULL, 0.06, NULL, '00.000.000.00', 'in_person_delivery', 9, 158.97, 0.00, 0.00, 0, NULL, 8, NULL, 3);
--
-- Table structure for table orders_products
CREATE TABLE IF NOT EXISTS orders_products (
orders_products_ID bigint(20) NOT NULL AUTO_INCREMENT,
op_order_id bigint(20) unsigned NOT NULL,
op_products_id bigint(20) unsigned NOT NULL,
op_products_mfr_part_number varchar(65) NOT NULL,
op_products_name varchar(15) NOT NULL,
op_products_qty bigint(10) unsigned NOT NULL,
PRIMARY KEY (orders_products_ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5923 ;
--
-- Dumping data for table orders_products
INSERT INTO orders_products (orders_products_ID, op_order_id, op_products_id, op_products_mfr_part_number, op_products_name, op_products_qty) VALUES
(1, 1, 491, 'CWP8489A001BA', 'X25', 1),
(2, 2, 2134, 'Professional Fee', 'Professional Fe', 3),
(3, 3, 473, 'CWPDR360', 'DR-360', 1),
(4, 4, 2134, 'Professional Fee', 'Professional Fe', 1),
(5, 5, 362, 'CWPDR360', 'DR-360', 1);
--
-- Table structure for table products
CREATE TABLE IF NOT EXISTS products (
products_id bigint(20) NOT NULL AUTO_INCREMENT,
products_brand varchar(200) NOT NULL,
products_brand_type varchar(200) NOT NULL,
products_mfr_part_number varchar(65) NOT NULL,
products_common_name varchar(15) NOT NULL,
products_msrp decimal(11,2) NOT NULL,
products_price decimal(11,2) NOT NULL,
products_description varchar(255) NOT NULL,
products_weight decimal(11,2) NOT NULL DEFAULT '1.00',
products_length decimal(3,2) DEFAULT NULL,
products_width decimal(3,2) DEFAULT NULL,
products_height decimal(3,2) DEFAULT NULL,
products_tax_exempt int(11) DEFAULT NULL,
PRIMARY KEY (products_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2558 ;
--
-- Dumping data for table products
INSERT INTO products (products_id, products_brand, products_brand_type, products_mfr_part_number, products_common_name, products_msrp, products_price, products_description, products_weight, products_length, products_width, products_height, products_tax_exempt) VALUES
(1, 'HP', 'Original', '92298A ', '98A', 132.99, 131.66, 'Genuine HP® LaserJet 98A Black Toner Cartridge (92298A) ', 4.20, 9.99, 6.14, 9.72, NULL),
(2, 'HP', 'Original', 'C3903A ', '03A', 112.99, 111.86, 'Genuine HP® LaserJet 03A Black Toner Cartridge (C3903A) ', 3.00, 9.99, 4.80, 7.72, NULL),
(3, 'HP', 'Original', 'C3906A ', '06A', 87.99, 87.11, 'Genuine HP® LaserJet 06A Black Toner Cartridge (C3906A)', 2.13, 9.99, 5.16, 6.50, NULL),
(4, 'HP', 'Original', 'C3909A', '09A', 254.99, 252.44, 'Genuine HP® LaserJet 09A Black Toner Cartridge (C3909A)', 3.31, 9.99, 4.72, 8.07, NULL),
(5, 'HP', 'Original', 'C4092A ', '92A', 75.99, 75.23, 'Genuine HP® LaserJet 92A Black Toner Cartridge (C4092A) ', 2.20, 9.99, 5.16, 6.50, NULL);
The major problem is that you need a join condition between orders_products and orders. You have a , which is equivalent to cross join. As a simple rule: never use commas in the from clause.
In addition, the where clause was awkwardly phrased. Here is a rewrite of your query that also uses table aliases for readability:
SELECT op.op_products_name, op.op_products_id, SUM(op.op_products_qty) AS TotalSold
FROM orders_products op JOIN
orders o
ON op.op_order_id = o.orders_id
WHERE o.orders_date_purchased BETWEEN '2012-11-05 00:00:00' AND '2012-11-10 00:00:00'
GROUP BY op.op_products_id
ORDER BY TotalSold DESC;
I will send an email to my client when approaching the measurement date with php. Something measurement valid one year, something valid 3 years, etc... therefore one company's data one row. But I would like write, that how many days valid his measurement.
I hope yours understand my problem. Thanks in advance! Adam
I have a table with structure:
CREATE TABLE IF NOT EXISTS `meresek` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`COMP_ID` varchar(4) NOT NULL COMMENT 'What a company ID',
`Comp_V` int(11) NOT NULL DEFAULT '1' COMMENT 'What size number of sites',
`MERES_1` date DEFAULT NULL,
`MERES_END_1` date DEFAULT NULL,
`EV_MERES_2` date DEFAULT NULL,
`MERES_END_2` date DEFAULT NULL,
`MERES_3` date DEFAULT NULL,
`MERES_END_3` date DEFAULT NULL,
`MERES_4` date DEFAULT NULL,
`MERES_END_4` date DEFAULT NULL,
.
.
.
.
`MERES_END_8` date DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `COMP_ID` (`COMP_ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=70;
INSERT INTO `meresek` ( `ID`, `COMP_ID`, `COMP_V`,`MERES_1`
`MERES_END_1`,
`EV_MERES_2`,
`MERES_END_2`,
`MERES_3`,
`MERES_END_3`,
.
.
.
`MERES_END_8) VALUES
(1, 'X1', 1, NULL, NULL, '2011-03-07', '2011-03-31', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL),
(2, 'X2', 1, NULL, NULL, '2010-12-19', '2019-12-31', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL),
(3, 'Y11', 1, NULL, NULL, '2011-05-12', '2014-12-31', NULL, NULL, NULL, NULL, '2011-05-12', '2020-05-12', '2011-05-12', '2020-05-12', NULL, NULL, NULL, NULL),
(4, 'Y12', 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2012-02-02', '2013-02-02', '2012-02-02', '2013-02-02')
select least(
coalesce(col_1,col_2....col_8),
coalesce(col_2,col_1....col_8),
coalesce(col_3,col_1....col_8),
coalesce(col_4,col_1....col_8),
coalesce(col_5,col_1....col_8),
coalesce(col_6,col_1....col_8),
coalesce(col_7,col_1....col_8),
coalesce(col_8,col_1....col_1)) where id = '35'