getting started with loops and iteration in sequel pro - mysql

I'm using sequel pro to select data from several tables. There are two things I need to do that seem to need a loop of some kind. I have never used any form of iteration in sql and can't find a beginners-level resource to learn from.
Can anyone suggest how to do the following two tasks, or suggest a tutorial where I can learn the fundamentals and figure it out from there:
Task 1: Go through a version history table, find the relevant history record for a given id that applied at a given date, and select the value from that record. The form of the history table is:
id, Item_id, version-created_at, value
eg
1, 123, 2014-05-01, 754
2, 456, 2014-05-10, 333
3, 123, 2014-05-27, 709
and I need to find what the value of item 123 was on the date 2014-05-25 (ie I need to find record id=1 and value = 754 because that is the most recent version for item 123 created prior to my target date.
So I figure I need to run through the table looking for item 123 and comparing dates of those records. But I don't know how to deal with the iteration of moving from one record to the next and comparing them.
Task 2: Go through a single text field that contains a number of product id and matching product prices in a string, and find the id of the product with the lowest price. Form of the string is a series of pairs of price "p" and id "i", in random order, like this:
"
- :p: 99.8
:i: 3
- :p: 59.0
:i: 5
- :p: 109.8
:i: 18
- :p: 82.45
:i: 46
"
and in this example I need to find "5", being the id of the product with the lowest price $59.
So I figure I need to step through each of the p/i sets, maybe by counting characters, but I have no idea how to iterate through and compare to find the best price.
A little help would go a long way.
Thanks.

For first answer you can do something like this:-
SELECT value FROM history where id = 123 AND version-created_at = '2014-05-01';
and for another task you must try this at front end rather than at back end.

Related

MySQL question, How to loop through a list and return number of occurances for each in a table

I have a list of values.
'abc123', 'bdg432', 'eds321', 'hgd765', 'fds987', 'tdq343'
These values exist many times in a field in the "Items" table called "Itmcode".
I would like to execute the following query for each of the items codes from the list above.
SELECT
Items.Itmcode,
COUNT(*) AS `Total Items Sold`
FROM
Items
WHERE
Items.Itmcode = {Item Code From List} AND
Items.ItmStatus > 2
getting a result as follows.
Itmcode
Total Items Sold
abc123
4248
bdg432
98
eds321
78427
hgd765
151
tdq343
72164
I am pretty sure I need to use a loop to do this but i am not sure how.
I have never tried using loops before. I have looked at a commonly referenced example of a stored procedure that creates a list of numbers and outputs them into a string. For whatever reason I cant transfer that concept to reality. I am hoping that someone here can give help me to understand what I think is probably the simplest answer in the universe. I am just not getting it.

How do I select rows that contain any of the selected values in any of the selected columns? MySQL

I'm pretty much trying to get all of the rows that contain any of the relevant tags in any of the relevant columns.
Take a look at an example row:
[LeadID Leadname Ratings AvgRating Address Website Phone TimesOpen Category LeadDescription CurrentStatus]
1 Siena Tuscan Steakhouse 396 4.300 104 S Broadway, Wichita, KS 67202, United States http://www.sienawichita.com/ +1 316-440-5300 LGBTQ+ friendly2022-05-19 Thursday 5PM–12AM
2022-05-20 Friday 6:30–10AM
2022-05-21 Saturday 7–11AM
2022-05-22 Sunday 7–11AM
2022-05-23 Monday 6:30–10AM
2022-05-24 Tuesday 6:30–10AM
2022-05-25 Wednesday 5PM–10AM
restaurants Hotel restaurant-bar offering refined Italian plates & many wines in a warm & elegant atmosphere.
I don't think you'll need to see it in structured form so I apologize for it being messy.
Everything in [ ] are the column names, and the following are its respective fields.
Here is my query
SELECT LeadID
FROM cleancopy
WHERE
Website OR LeadName OR LeadDescription OR Category
IN ('%Event%' OR '%Live%' OR '%Music%' OR '%Venue%');
This query is returning all rows unfiltered.
I want the query to select all rows that contain any number of the relevant tags "Event", "Live", "Music", "Venue", in any of the column names Website, LeadName, LeadDescription, Category.
So one or all of the tags could be in one or all of the attribute types.
More simply put, I'm trying to filter out any row that doesn't contain any of the keywords I want.
First thing: "I don't think you'll need to see it in structured form" is a very bad assumption. We DO need this because it makes it much easier to provide a good answer.
Second thing: This is not the kind of data checking SQL is done for. So there is no simple way especially when you really need a list of strings and a like condition. Such complex data handling should better be avoided or done outside SQL and within the application.
Anyway, the shortest way to do what you describe will be to CONCAT all columns and then search for your strings using OR.
SELECT leadid FROM cleancopy WHERE
CONCAT(website,leadname,leaddescription,category) LIKE '%Event%'
OR CONCAT(website,leadname,leaddescription,category) LIKE '%Live%'
OR CONCAT(website,leadname,leaddescription,category) LIKE '%Music%'
OR CONCAT(website,leadname,leaddescription,category) LIKE '%Venue%'

End of Record Indicator in MySQL Query

I'm trying to write and automate a MySQL query that gets ingested by some downstream reporting platforms. The platform requires the CSV to have an end or record indicator (EOR) to show the last record in the document. They're wanting a dollar sign ($) to indicate the EOR and, while it's easy to manually enter that, I want to automate the report but can't seem to find a way to enter the $ in the last row, last cell. Any ideas?
Example:
First name
Last name
DOB
Mike
Smith
1-1-1900
Mike
Jones
1-1-1900
$
Just append it with a UNION ALL statement -
<YOUR_SELECT_QUERY>
UNION ALL
SELECT '$', <NULLS FOR OTHER_COLS>;
You have to use as many NULLS in your last union statement as there are columns in your first query to match the no of columns in your query.

Is possible to remove duplicates in Power BI based on a time interval between the data?

I have a list of leads data.
The table has a lot of infos like date, name, email, mobile number, etc.
However, some of these leads are duplicates: the same person generated more than one lead
What i want to do is to remove the duplicate leads.
The problem is, to be considered a duplicated lead, the email or the mobile number must appear in more than one row, in a time interval of 30 days.
And only those who come next must be considered duplicated. The first one is always a not duplicated lead.
E.g.
1) If Jones generated a lead in 01/01/20 with his email abc#abc.com and then generate another lead 10 days after, in 10/01/20. The first lead is a single lead (not duplicated) and this second lead must be considered duplicate.
2) If Maria generated a lead in 01/01/20 with her email xyz#abc.com and then generate another lead 40 days after, in 10/02/20. The first lead is a single lead (not duplicated) and this second lead also must be considered single (or not duplicate).
To mark the lead as duplicate or not, i want to generate a new column with the time between the last lead of the same person (same email or same mobile number)
Then generate a new column with the label "Duplicate" or "Not Duplicate" based on the time showed on the last column. If its > than 30 days, that is a single lead. Otherwise (<30 days) is a duplicate lead.
E.g picture:
Can someone please help me on how to do that?
Getting the lag/lead data is not very straight forward in Power BI. You will have to use a combination of EARLIERand some aggregate function to get the specific result. For your specific scenario, the following calculation might work:
Day Difference =
VAR name1 = 'Table'[Name]
VAR Lastdate1 = MAXX(FILTER('Table','Table'[Name]=name1 && 'Table'[date]<EARLIER('Table'[date])),'Table'[date])
RETURN
IF(
DATEDIFF(Lastdate1,'Table'[date],DAY)=BLANK(),
100,
DATEDIFF(Lastdate1,'Table'[date],DAY))
Once the column is created, you can filter for all records <=30 to get the result you are looking for. I have replaced the blanks with 100, so that the original records don't get removed when applying the condition.
If you are looking for the "Tag" value, then the following calculation will get you the tag values directly:
Tag =
VAR name1 = 'Table'[Name]
VAR Lastdate1 = MAXX(FILTER('Table','Table'[Name]=name1 && 'Table'[date]<EARLIER('Table'[date])),'Table'[date])
RETURN
IF(IF(
DATEDIFF(Lastdate1,'Table'[date],DAY)=BLANK(),
100,
DATEDIFF(Lastdate1,'Table'[date],DAY))<=30,"Duplicate","Single")

Sorting/Ordering sequenced pairs of data in MySQL?

I am trying to determine if there's a way to sort rows of a MySQL table that consists of start/finish columns. (Could also be thought of as parent/child relations or other linked list arrangement)
Here's an example of how the data is currently stored:
id start finish
2 stepthree stepfour
6 stepfive stepsix
9 stepone steptwo
78 stepfour stepfive
121 steptwo stepthree
(The id numbers in this are not relevant, just using them to indicate additional columns of arbitrary data)
I want to sort/display these row in order, presuming I am always starting with "stepone", that traverses the start-> finish chain like, each "finish" being followed by the row with it as a "start".
desired output
9 stepone steptwo
121 steptwo stepthree
2 stepthree stepfour
78 stepfour stepfive
6 stepfive stepsix
There shouldn't be any branching/splits normally, just a sequential series of steps or states. I can't use simple alpha sorting (in my case the start and finish values are codes created by a customer), but can't figure out any other way to order these using SQL. I could programmatically do it using most languages, but stumped about doing it just with SQL.
Any clever ideas?
I would recommend having another table that has each step mapped to its precedence order.
Then you can write a query to sort each row in the order of precedence of the start step.