Generate Sequential IDs for Line Items on a Per Customer Basis in SQL Server - sql

Apologies if the title is difficult to understand... it proved challenging to summarize my question.
The business has created a self-reporting spreadsheet to give out to our stores to track customer leads. Each row represents one follow-up action, therefor each customer can have multiple rows. Employees were not properly filling out the follow-up counter column (e.g. they'd forget they already spoke to somebody or someone else followed up a previous lead so one customer would have two rows labeled as follow-up #1) so we eliminated it and I'm now using a concatenation of date and sequential rowID column to order their interactions.
I would like to be able to derive follow-up #s with this data. I am now able to easily order the data by Customer, Date, and RowID to get an accurate flow of follow-ups, but I would like to now number those rows 1 through X so I can perform analysis and aggregate on the follow-up counter.
Simplified example of customers ordered with their Date/ID:
Please click link for example 1 (not enough rep to embed yet)
How could I then, with the data above, create the following:
Please click link for example 2 (not enough rep to embed yet)
I'd love to be able to derive the follow-up counters after the fact via SQL or T-SQL. Any ideas? Thank you.

Take a look at Window Functions, particularly ROW_NUMBER.
I believe you're looking for something like this:
SELECT
[Customer Name],
[date_id_concat],
ROW_NUMBER() OVER (PARTITION BY [Customer Name] ORDER BY [date_id_concat]) AS InteractionSeq
FROM
TABLE;

Related

SQL Method for Cascading Workload Based on Rank and Available Hours

Recently I created an automated production scheduling tool through Excel that assigns a rank to items being produced in the same process, and then uses that rank in combination with the workload to create a schedule.
It functions exactly the way it is intended to, but due to the large amount of data and it being excel it has very slow performance, which is why I am looking to move the calculations over to SQL.
The general logic is like this:
-Always produce everything from the first day before the second day
-Always produce items from an earlier rank before items from a later rank
You can see how this plays out in the image below, where the line has 21.5 hours today, so items will be produced on day 1 until it equals 21.5, where the remainder is then carried over to day 2 and so on.
I was able to do this in excel using lengthy positional based formulas, but I am trying to think of a way to get the same result in SQL without having to rely on looking at the row above.
I am not sure how to convey something like 'Subtract from the available time production time of higher priority items produced on the same day'.
I apologize if the question is unclear, but any advice would be appreciated.
Image of Production Hours Cascading by Priority and Day
Example of Position-Based Fomula
Thanks to shawnt00, that put me in the right direction. Ultimately I had to modify the case statements a bit to go off of the cumulative total instead, but I was able to get the desired results using a sum() Over (partition by order by ) statement.

Tableau count values after a GROUP BY in SQL

I'm using Tableau to show some schools data.
My data structure gives a table that has all de school classes in the country. The thing is I need to count, for example, how many schools has Primary and Preschool (both).
A simplified version of my table should look like this:
In that table, if I want to know the number needed in the example, the result should be 1, because in only one school exists both Primary and Preschool.
I want to have a multiple filter in Tableau that gives me that information.
I was thinking in the SQL query that should be made and it needs a GROUP BY statement. An example of the consult is here in a fiddle: Database example query
In the SQL query I group by id all the schools that meet either one of the conditions inside de IN(...) and then count how many of them meet both (c=2).
Is there a way to do something like this in Tableau? Either using groups or sets, using advanced filters or programming a RAW SQL calculated fiel?
Thanks!
Dubafek
PS: I add a link to my question in Tableu's forum because you can download my testing workbook there: Tableu's forum question
I've solved the issue using LODs (specifically INCLUDE and EXCLUDE statements).
I created two calculated fields having the aggregation I needed:
Then I made a calculated field that leaves only the School IDs that matches the number of types they have (according with the filtering) with the number of types selected in the multiple filter (both of the fields shown above):
Finally, I used COUNTD([Condition]) to display the amounts of schools matching with at least the School types selected.
Hope this helps someone with similar issue.
PS: If someone wants the Workbook with the solution I've uploaded it in an answer in the Tableau Forum

Access Database - Most Recent Record - Max Function

I'm in the process of building a database to keep track of loaning equipment. I'm trying to build a query that will display the latest record of each machines location.
Relevant table is:
Movements:
Movement ID (PK)
EntryDate (Automatically generated on record entry)
Serial (FK from a table called stock, with (Make, Model etc)
Location (Where the machine is)
Status (Things like: Available, Testing, Sold etc)
Current query is:
SELECT Movements.Serial, Max(Movements.EntryDateMovements) AS MaxOfEntryDateMovements
FROM Movements
GROUP BY Movements.Serial;
Which spits out the latest date of a record, and the serial associated with it.
What I need is the status to be shown in the results, but it still be grouped by the serial.
My issue is that when I try and add that, it either comes back with an error with about the expression not being part of the aggregate function, or I get more results than expected, as it no longer just keeps the results unique to the serial.
I'm pretty new Access, and have so far been able to muddle through guides, and books, and this site, to get everything else working, but i'm stuck at this hurdle.
Any help would be much appreciated.
Select top 1 *
from Movements
order by EntryDateMovements desc
This will give you everything for the newest record. This is TSQL but I think it carries over to Access.
Try this
Select t.serial,t.EntryDateMovements ,t.location, t.status
From movements as t
Inner join (SELECT Movements.Serial, Max(Movements.EntryDateMovements) AS MaxOfEntryDateMovements
FROM Movements
GROUP BY Movements.Serial) as MaxMovements on t.serial= MaxMovements.serial and t.EntryDateMovements=MaxMovements.MaxOfEntryDateMovements

SQL query for the number of cases when a value of column1 (non-unique) can't be found within any record where column2 meets a basic criteria

I am doing a beginners' SQL tutorial and I started to wonder whether a simple SQL query on this table: http://www.sqlcourse2.com/items_ordered.html could tell the number of items (also 1) which have only been purchased more items at a time, so there is no record which contains the quantity column with a value of 1 AND the item. I am really beginner at this so please try to keep it simple.
Thank you in advance!
Welcome to the fascinating world of SQL.
Well - I'm not giving you the answer, but a hint (after all, it's a training and your own thinking and finding the solution would be the best way for you to learn something new).
The way you formulate your question is somewhat puzzling.
When I combine what you ask with what is possible with SQL, the question that would make sense to me would be that you need to list (or count, I did not understand that very well) the items (or the complete rows in the table with matching item, that was not clear either), that were never sold with a quantity of 1.
If that's what you need, you will need a subselect to get all distinct items that were sold with a quantity of 1, and select the rows from your base table whose item value is not in the list you get from the subselect.
Do you need more hints?
Marco

SQL Server 2012 Managment Studio Basic SELECT queries

I am new to SQL Server. I have been assigned to do some simple queries to start off, then eventually move on to more complex queries.
I have spent a lot of time on this website: http://www.w3schools.com and I understand it, I think, but then when I go back to my company's database, I find myself searching from many, many, different tables with different information.
For example, a table would say [Acct_Name] and the query comes back with not the correct account name (s) that I need. Any advice that you think might help me? Thank you.
It sounds like you are looking to limit your results to specific accounts. There are many ways to go about this, so no one will be able to give you a all encompassing answer but if you are looking to just pull a single account
SELECT * FROM (your table name) WHERE Acct_Name = 'the account name'
The * means you are selecting all columns in the table and your WHERE clause is where you set your search conditionals, like account name or by account ID. If you had a account creation date, you could get all accounts created on or before a date like this
SELECT * FROM (your table name) WHERE Created < '2016-06-01 00:00:00'
Replace the column name 'Created' with the column that holds the date field of account creation
Learning the WHERE clause and what you can do there to limit your results will get you on a solid footing to start, from there you will want to learn JOINs and how to link tables by primary keys.
Code academy has some great tutorials https://www.codecademy.com/learn/learn-sql