End of Record Indicator in MySQL Query - mysql

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.

Related

SQL/mysql - how to display two columns with different value from 1 table

I am trying to make a query for approval of documents, where the result display the name and signature with date. How can I get the date for two people approving the document?
Select Uname
case when stepcode=1 then 'approver1' end as 'name of person'
case when stepcode=1 then 'approver1' end as ' date of signed noted'
case when stepcode=2 then 'approver2' end as 'date of signed approved'
from table
I tried this, but only one result showed up. Only the name, signature and date of the first approval displayed.
We can only answer this by making some assumptions:
the field stepcode denotes what stage of the sign off process the record is at
value of 1 means noted and value 2 means approved. A value of 0 means nothing has happened yet
approver1 and approver 2 are NULL if the action has not yet taken place
If all of the above is true, then there should be no requirement to have a CASE statement for the fields... just including the fields within the SELECT statement will bring the values through if they have been completed.
Some validation of data might be required here though if you are not getting the results you are expecting. Running some rough counts for each of the steps and for where they have values in the approver fields would help to make sure your code is working. The following should give you something to work with:
SELECT
stepcode
COUNT(TableID) AS NumberAtStep
FROM table
GROUP BY stepcode
Using these counts, you can then run your statement without the CASE statements and run a manual count to ensure you are seeing the right number of records with the relevant populated columns for each step.
Further information will be required to delve into your problem further however

How to check whether a value exists among a set of values in a record in mysql

I am using MySQL in such a way that the user enters a date and flights appear on that day.I was too lazy to put many dates so what I did was made certain flights run on certain days.
The table planes contains many columns out of which dtd(column containing many days of type varchar(50)) .
One record(in dtd) is Monday, Tuesday
The user enters the date 2018-12-03 which is a Monday.
My problem is how do I extract only the record which has Monday?(like the monday,Tuesday one)??
I tried select.....where instr(day(2018-12-03),dtd)<>0 but I realised that instr gives 0 in 2 cases
1. the character(s) is not present in the record or
2.occurence is at the beginning.
Like instr(h,hello) and instr(a,hello) gives 0.
Please help
I suggest that you use the LIKE operator.
For more info about it please check this link: SQL Like Operator
To solve your problem, you can try the following:
SELECT ...
WHERE dtd LIKE CONCAT('%', day(2018-12-03), '%');
In this case, you will get all the rows of the table, where the value of the field dtd contains the value of day(2018-12-03).
Hope this helps!

Dynamically change column names as week number on every weekly run

I want to build a SSRS report that has column as week numbers - 8 weeks for 8 columns starting with current. This report is run every week and current week number is set then. So both column names and their values should change .Is it possible to build something like this in SSRS?
I tried doing this with a dynamic SQL based stored proc in dataset. However for every run I don't even see the columns values updating dynamically
Here's an example :
Also I am trying to avoid these week numbers as row values and then using matrices
My stored proc looks something like this
declare #n tinyint = datepart(wk, getdate())
declare #n1 tinyint = (#n+1), #n2 tinyint =(#n+2), #n3 tinyint =(#n+3), #n4 tinyint =(#n+4), #n5 tinyint =(#n+5), #n6 tinyint =(#n+6)
exec ('Select b.sku, b.['+#n+'], b.['+#n1+'], b.['+#n2+'], b.['+#n3+'], b.['+#n4+'], b.['+#n5+']...
Will appreciate any help in this direction.. many thanks!
When working with SSRS it's generally best to avoid dynamic SQL and pivoting the data in the SQL. Use the SQL to get the raw data you need and then let SSRS do the pivoting and aggregation. This way you take advantage of what they each do best. I know you said you want to avoid matrices, but it is the best way to make the report dynamic.
So you should either return all the data in one dataset and use filters on your matrices OR write two queries and have each one populate a matrix. BTW a matrix is just a table with a column group added, so don't be intimidated by them.
There are 2 ways to do this with a standard tablix.
Calculate the column headers as expressions using concatenation of Wk and some date math to find the correct week number and return the same sort of thing from your query (e.g. columns are current_week, week_minus_1, week_minus_2...)
Return the column headers as additional columns in your query that are the same value for every row (e.g. ColHeader0, ColHeader1...). Your data columns would still be relative weeks (e.g. ValueWeek0, ValueWeek1...). In your report the column header would have an expression like =First(Fields!ColHeader0.Value). This is a more flexible approach since it lets you pick 8 historical weeks instead of only the last 8 weeks if you add a parameter.
EDIT - Clarifications
The reason that you get the blank column Wk48 is approximately that you have created your report looking for that column that won't be there the next time. SSRS looks for exact columns. You should you use relative column names for either of the options I have specified:
exec ('Select b.sku, b.['+#n+'] as Wk0, b.['+#n1+'] as Wk1, b.['+#n2+'] as Wk2, b.['+#n3+'] as Wk3, b.['+#n4+'] as Wk4, b.['+#n5+'] as Wk5...
This will allow you to populate the aliased Wk0 column with the appropriate current week data and still make sure that it can be consistently referenced as the base week by SSRS.
To change the column headers you can:
Independently calculate the week numbers in SSRS in the column header expressions: ="Wk" + CStr(<correct week calculation>).
Return the column headers in the result set and access them in the column header expression:
exec ('Select b.sku, b.['+#n+'] as Wk0, b.['+#n1+'] as Wk1, b.['+#n2+'] as Wk2, b.['+#n3+'] as Wk3, b.['+#n4+'] as Wk4, b.['+#n5+'] as Wk5..., ''Wk'''+#n+' as ColHeader0, ''Wk'''+#n1+' as ColHeader1...
and reference the returned column headers from the SSRS column header expression as =First(Fields!ColHeader0.Value).
Here's a solution that worked for me:
Create parameters (say CurrWk, CurrWk1) ,set as hidden and store 'Default value' and 'Available value' equals to current week number (datepart(wk, now()) and any subsequent week by doing a +1, +2, +3.. etc.
Write a query expression . Click onto fx beside dataset query space and write the select query for your program embedding parameter values in the expression window. For eg ="Select SKU, [" & Parameter!CurrWk.Value & "] as Wk1,
[" & Parameter!CurrWk.Value & "] as Wk1 from Sales_Table"
Before passing this query as a 'command text expression' please ensure this query is working in sql ssms.
Save the expression. Now find 'Fields' tab on the left hand side panel.You need to map the fields manually from the query here. If this is not done, there is a very high chance you seean empty field list and wont be able to access them at all. This may be because ssrs do not store query metadata directly from expressions.
You can avoid part of the issue by having atleast the static fields , for example here SKU listed in the 'Fields' list by first running a sql query with static field(select SKU from Sales_Table ). You can then go back to update dataset- change query to expression and embed the parameterized field names.
Map field names. In this example I chose 'Query Type' fields and set Field names as SKU, CurrentWeek, NextWeek and mapped to source SKU, Wk and Wk1 respectively.
Click on 'Refresh Fields' at the bottom. Now you have a dataset with the complete field list. Use these in charts, tables . Run it every week and note the numbers changing as expected.
In case you are using this dataset in a table, make sure you set headers with Labels of Parameters (for eg here I did =Parameters!CurrWk.Label for col with current week data)
That's it!

getting started with loops and iteration in sequel pro

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.

SSRS: How to select two or more values from a long filtered multiple selection list with different search strings

Let's consider a multiple selection parameter on a report: Employee
This parameter has a lot of possible values. Initially nothing is shown on the list and there is a textfield search parameter associated, that updates the Employee selection list with top n matches for the searched string.
If the entered search query is John Doe we can imagine that now the selection list shows:
John Doe
...
Xavier John Doesson
Now I can select as many items as I want from this filtered list, but if I want to select both John Doe and Alicia Keys happens the following:
First when I enter the search string "John Doe" the selection list gets populated accordingly
I select John Doe - OK
I enter search string "Alicia Keys", the selection list gets populated also
Selection of John Doe is gone - I want to be able to select both Alicia and John at the same time, but I don't want to go through a thousands of names long selection list
Update:
Forgot to mention that we have an OLAP cube in the background with dimension 'Employee'. This dimension is used as the source of the parameter and the param dataset uses MDX to fetch the values, therefore the SQL solution cannot be applied here.
The current solution creates an custom set with MDX Filter and Head functions and then this set is used in the ROWS-part of the MDX query.
Here is how the set created:
SET setEmployees AS {
HEAD(
FILTER( [Employees].[Employees].ALLMEMBERS,
INSTR([Employees].[Employees].CURRENTMEMBER.Name,#EmployeeSearch,1 >= 1 )
)
,100)
}
Basically the problem with this solution is that how do you add multiple search strings to the instr function
Is there a common solution to this kind of situation? Am I approaching the problem from wrong direction?
What you could do is make the search parameter more flexible, so you can handle input such as:
John OR Jane
If "OR" queries are more common than "AND" queries you could support it with queries such as:
John Jane
Note that this may throw people off, because the search features they're used to (such as Google search) typically tend interpret multiple words in the "AND" sense.
Anyhow, the tricky bit of course is the SQL behind the Employee data set. This should use the search parameter in a more flexible way. You haven't specified how that's currently working, but I imagine you may be using something like:
WHERE Employee.FullName LIKE '%' + #SearchParameter + '%'
You would need to extend that to support "OR" queries. There's a whole range of solutions for that, from quick 'n dirty handmade SQL (e.g. string split combined with WHERE...IN) to full-text querying. Choose a solution that's best for your situation.
If you have a fixed number of search terms than you can do something like the following.
FILTER( [Employees].[Employees].ALLMEMBERS,
INSTR([Employees].[Employees].CURRENTMEMBER.Name,#EmployeeSearch1,1 >= 1) OR
INSTR([Employees].[Employees].CURRENTMEMBER.Name,#EmployeeSearch2,1 >= 1)
)
Even if you can do that, I do not recommend it. You don't have the luxury to index Analysis Services like you do SQL. A better possible approach would be to query your data warehouse for the employees and return the appropriate keys, and then filter by those keys in your MDX statement.