SQL-Server 2012 Subtracting Rows - sql

I have some counts that get periodically recorded into SQL and I'm trying to find out the difference between the start count and the final count.
Raw Data Below
This table has around 30 columns but they are the more of the same just different counts.
I want to take the min and max row for a time period based on user input from an SQL report I can filter out the data with the code below. (I can also filter it into two different tables, one with min, and one with max if that is easier.)
SELECT *
FROM #tempTable
WHERE TableIndex = (SELECT min(TableIndex) FROM #tempTable)
or TableIndex = (SELECT max(TableIndex) FROM #tempTable)
Filtered Data Below
The end goal is the difference between these two rows, I would then give that data to an SQL report to display a bar graph.
I've seen solutions but they seemed overly complex for what I'm trying to do and I would need to define each column I'm subtracting vs using *. Some of the tables have a couple hundred columns.

How about joining these together?
SELECT tt.*, ttm.*
FROM #tempTable tt
(SELECT min(TableIndex) as minti, max(TableIndx) as maxti
FROM #tempTable
) ttm
ON ttmTableIndex IN (ttm.minti, ttm.maxti);
You can then do whatever arithmetic operations you like with the values in the same row.
Personally, I would find it easier to just put the two rows into a spreadsheet and subtract the values using a formula.

Related

Optimal SQL query for querying 31 tables (containing datestamp in tablename)

Fairly new to SQL and I was stumped on this question I received in an interview recently.
The question was along the lines of how would you count the total occurrences of 'True' for Column B in July.
Problem was; there was no date or timestamp column in the table. Instead the table naming convention was defined as "ProductX_YYYYMMDD". The assumption being that a new table is created for each day's data dump.
Is there an efficient query I can write to obtain the True COUNTs of Column B for each table (which doesn't involve ~30 JOIN or UNION statements to get the answer)?
Use STRING_SPLIT(myColumn, '_')
Then
SELECT RIGHT (SELECT LEFT(tempColumn, -4)), -2)
Now you have a temp table filled with only month |MM| and you can use
COUNT() FROM dailyTable WHERE dailyName like '07'
Add the count of every daily Table to a variable

Best way to compare two tables in SQL by matching string?

I have a program where the goal is to take data from an API, and capture the differences in data from minute to minute. It involves three tables: Table 1 (for new data), Table 2 (for previous minutes data), Results table (for the results).
The sequence of the program is like this:
Update table 1 -> Calculate the differences from table 2 and update a "Results" table with the differences -> Copy table 1 to table 2.
Then it repeats! It's simple and it works.
Here is my SQL query:
Insert into Results (symbol, bid, ask, description, Vol_Dif, Price_Dif, Time) Select * FROM(
Select symbol, bid, ask, description, Vol_Dif, Price_Dif, '$now' as Time FROM (
Select t1.symbol, t1.bid, t1.ask, t1.description, (t1.volume - t2.volume) AS Vol_Dif, (t1.totalPrice - t2.totalPrice) AS Price_Dif
FROM `Table_1` t1
Inner Join (
Select id, volume, ask, totalPrice FROM Table_2) t2
ON t2.id = t1.id) as test
The tables are identical in structure, obviously. The primary key is the 'id' field that auto-increments. And as you can see, I am comparing both tables on the basis of these 'id' fields being equal.
The PROBLEM is that the API seems to be inconsistent. One API call will have 50,000 entries. The next one will have 51,000 entries. And the entries are not just added to the end or added to the beginning, they are mixed into the middle.
So, comparing on equal ID's means I am comparing entries for DIFFERENT data, IF the API calls return a different number entries.
The data that I am trying to get the differences of is the 'bid', 'ask', 'Vol_Dif', 'Price_Dif' from minute to minute. There are many instances of the same 'symbol's, so I couldn't compare with this. The ONLY other way to compare entries from table to table, beside the matching ID's, would be matching the "description" fields.
I have tried this. The script is almost the same as above except the end of the query is
ON t2.description = t1.description
The problem is that looking for matching description fields takes 3 minutes for 50,000 entries, whereas looking for matching ID's takes 1 second.
Is there a better, faster way to do what I'm trying to do? Thanks in advance. Any help is appreciated.

Get latest data for all people in a table and then filter based on some criteria

I am attempting to return the row of the highest value for timestamp (an integer) for each person (that has multiple entries) in a table. Additionally, I am only interested in rows with the field containing ABCD, but this should be done after filtering to return the latest (max timestamp) entry for each person.
SELECT table."person", max(table."timestamp")
FROM table
WHERE table."type" = 1
HAVING table."field" LIKE '%ABCD%'
GROUP BY table."person"
For some reason, I am not receiving the data I expect. The returned table is nearly twice the size of expectation. Is there some step here that I am not getting correct?
You can 1st return a table having max(timestamp) and then use it in sub query of another select statement, following is query
SELECT table."person", timestamp FROM
(SELECT table."person",max(table."timestamp") as timestamp, type, field FROM table GROUP BY table."person")
where type = 1 and field LIKE '%ABCD%'
Direct answer: as I understand your end goal, just move the HAVING clause to the WHERE section:
SELECT
table."person", MAX(table."timestamp")
FROM table
WHERE
table."type" = 1
AND table."field" LIKE '%ABCD%'
GROUP BY table."person";
This should return no more than 1 row per table."person", with their associated maximum timestamp.
As an aside, I surprised your query worked at all. Your HAVING clause referenced a column not in your query. From the documentation (and my experience):
The fundamental difference between WHERE and HAVING is this: WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed.

SQL Query to count multiple values from one table into specific view

I like to request your help. I can get the results seperated but now i want to create a query which has it perfect for a external person. my explanation:
I have a statistics database with in this database a table when some records comes in and each records has several columns with values etc...
Now one of these columns is called "MT"
MT Column can have only one of the following values per records: A,B,C,D,E
The records also have a columne called TotalAmount which indicate a size of a value outside the database. This TotalAmount column is numeric without decimals and can have a value between 1 and 10.000.
And the last part is the records it self, the table has X amount of records.
So Basicly i need to create a query which seperates each MT value and calculates the amount of records per MT and the sum of TotalAmount.
This is on SQL Server 2005.
Many thanks for your assistance!
Very hard to guess without a full db schema. But I think you need.
SELECT MT, Count(*), SUM (TotalAmout)
FROM YourTable
GROUP BY MT

How to find rows which differ by a given amount in SQL?

So I have a data table which looks like
Where each row has a timestamp column in Unix time. I need to find all the places where two entries with the same resource_id are x(day month, year etc) amount of time apart, so I need a query that will go through and look at the differences between one row and the next and spit back the ones which differ by more than a specified amount.
Anybody have any ideas on how to do this? Thanks in advance
You may use a cross join to compare every row in the table with every other row in the table then compare the field. For example the following will return where the two rows are 2 months apart.
SELECT t.resource_id, s.resource_id
FROM table t CROSS JOIN table s
WHERE TIMESTAMPDIFF(MONTH,t.timestamp,s.timestamp) = 2
Note that this could be extremely slow if the table is large. Or according to the MySQL docs just saying JOIN without specifying the condition will result in a cartesian product which is equivalent to a cross join.