SQL data sorting by column [duplicate] - sql

This question already has answers here:
How does sql server sort your data?
(4 answers)
Closed 5 years ago.
I am facing one issue I cant handle yet.
Here's the deal: I am working on a program which should monitor employees working hours. So far, I created a SQL Server table called TablicaSQL with 4 columns:
Id, Ime (Name), Datum (date), BrojSati (WorkingHours)
It saves data according to the time of saving.
Example: if I enter Kristijan (name) worked on 2017-11-03 4 hours, but tomorrow if I save that Kristijan worked on 2017-11-01 4 hours, it will show which data has been saved first, which in this case is 2017-11-03.
So my question is: How can I sort my data according the column Datum (date), NOT by the date of saving the data.
Also, I am not looking for query which says something like this:
SELECT *
FROM..
ORDER BY...ASC/DESC
I need some kind of "permanetly asc/desc query".
Here is the screenshot of my table

There isn't a permanent order on database table. They are unorder data set. The data isn't order by the data of creation. Is just returned in the order is storage. But that can change if db engine optimizer find a better way to read the data. Multiple Partition, Clusters, etc.
If you want the data return in a specific order YOU MUST include ORDER BY

Related

MS Access - Log daily totals of query in new table

I have an ODBC database that I've linked to an Access table. I've been using Access to generate some custom queries/reports.
However, this ODBC database changes frequently and I'm trying to discover where the discrepancy is coming from. (hundreds of thousands of records to go through, but I can easily filter it down into what I'm concerned about)
Right now I've been manually pulling the data each day, exporting to Excel, counting the totals for each category I want to track, and logging in another Excel file.
I'd rather automate this in Access if possible, but haven't been able to get my heard around it yet.
I've already linked the ODBC databases I'm concerned with, and can generate the query I want to generate.
What I'm struggling with is how to capture this daily and then log that total so I can trend it over a given time period.
If it the data was constant, this would be easy for me to understand/do. However, the data can change daily.
EX: This is a database of work orders. Work orders(which are basically my primary key) are assigned to different departments. A single work order can belong to many different departments and have multiple tasks/holds/actions tied to it.
Work Order 0237153-03 could be assigned to Department A today, but then could be reassigned to Department B tomorrow.
These work orders also have "ranking codes" such as Priority A, B, C. These too can be changed at any given time. Today Work Order 0237153-03 could be priority A, but tomorrow someone may decide that it should actually be Priority B.
This is why I want to capture all available data each day (The new work orders that have come in overnight, and all the old work orders that may have had changes made to them), count the totals of the different fields I'm concerned about, then log this data.
Then repeat this everyday.
the question you ask is very vague so here is a general answer.
You are counting the items you get from a database table.
It may be that you don't need to actually count them every day, but if the table in the database stores all the data for every day, you simply need to create a query to count the items that are in the table for every day that is stored in the table.
You are right that this would be best done in access.
You might not have the "log the counts in another table" though.
It seems you are quite new to access so you might benefit form these links videos numbered 61, 70 here and also video 7 here
These will help or buy a book / use web resources.
PART2.
If you have to bodge it because you can't get the ODBC database to use triggers/data macros to log a history you could store a history yourself like this.... BUT you have to do it EVERY day.
0 On day 1 take a full copy of the ODBC data as YOURTABLE. Add a field "dump Number" and set it all to 1.
1. Link to the ODBC data every day.
join from YOURTABLE to the ODBC table and find any records that have changed (ie test just the fields you want to monitor and if any of them have changed...).
Append these changed records to YOURTABLE with a new value for "dump number of 2" This MUST always increment!
You can now write SQL to get the most recent record for each primary key.
SELECT *
FROM Mytable
WHERE
(
SELECT PrimaryKeyFields, MAX(DumpNumber) AS MAXDumpNumber
FROM Mytable
GROUP BY PrimaryKeyFields
) AS T1
ON t1.PrimaryKeyFields = Mytable.PrimaryKeyFields
AND t1.MAXDumpNumber= Mytable.DumpNumber
You can compare the most recent records with any previous records.
ie to get the previous dump
Note that this will NOT work in the abvoe SQL (unless you always keep every record!)
AND t1.MAXDumpNumber-1 = Mytable.DumpNumber
Use something like this to get the previous row:
SELECT *
FROM Mytable
INNER JOIN
(
SELECT PrimaryKeyFields
, MAX(DumpNumber) AS MAXDumpNumber
FROM Mytable
INNER JOIN
(
SELECT PrimaryKeyFields
, MAX(DumpNumber) AS MAXDumpNumber
FROM Mytable
GROUP BY PrimaryKeyFields
) AS TabLatest
ON TabLatest.PrimaryKeyFields = Mytable.PrimaryKeyFields
AND
TabLatest.MAXDumpNumber <> Mytable.DumpNumber
-- Note that the <> is VERY important
GROUP BY PrimaryKeyFields
) AS T1
ON t1.PrimaryKeyFields = Mytable.PrimaryKeyFields
AND t1.MAXDumpNumber= Mytable.DumpNumber
Create 4 and 5 and MS Access named queries (or SS views) and then treate them like tables to do comparison.
Make sure you have indexes created on the PK fields and the DumpNumber and they shoudl be unique - this will speed things up....
Finish it in time for christmas... and flag this as an answer!

Dynamic custom SQL in Tableau

I'm using Tableau 9.0 to connect to an Amazon Redshift database. The data is such a high volume that only the last 4 months is stored. Each month, a new table is created, named with the current month, and the table from 5 months ago is dropped.
So what we have right now is 4 tables:
events_jun
events_jul
events_aug
events_sep
The custom SQL that I want to define will use the UNION ALL function to merge all 4 tables together into a single query. The issue is that the table names will need to be changed month over month.
Is there a way to define variables based on CURDATE, such that you can take CURDATE() - 90 and extract the first 3 letters, then append it to the string "events_" in order to create a concatenated string that is the table name you want.
Please note, I have tried to resolve the problem by including a parameter in the custom SQL, as described here: http://onlinehelp.tableau.com/current/pro/online/mac/en-us/customsql.html
This does not work, because Tableau will surround the Paramter value with single quotes, which results in events_'jun' which of course throws an error, because there is not such table.

How can I return duplicate rows for a set of IDs? [duplicate]

This question already has answers here:
How can I remove duplicate rows?
(43 answers)
Closed 8 years ago.
I tried to google this but I didn't know how to write it without needing to explain myself.
Basically I have a data set that I am performing some validation on, and I am looking for duplicate data imports from users of the database I am working on.
The reason for this is that the users have been importing building information into the database. In some cases, the name (for example) has been incorrect, and so they have amended the import file and re uploaded the data.
The issue is that rather than replacing the existing building, the importer (understandably) creates new building records. So I need a way to return building records that have a duplicate, so that we can remove the older records.
Obviously this is not perfect, but I'm trying to use common fields (building size, location) to locate duplicates, as these fields would be the same; it's only the names that would have changed. So I if I were to have tables laid out as below, how would I isolate the duplicate rows? (sorry for the imgur link, I don't know how to format text here into a table-like format; the table is very much simplified)
http://imgur.com/cOpXZAr
So you can see that the buildings at LocationID 1 and 4 have only been imported once, but the import for LocationId 2 has been run twice and 3 times for LocationID 3 - these are the records I need to find.
I simply want to know if there is something I can use to isolate rows where a series of columns are duplicated - can anyone help?
This gives you the duplicates:
select *
from TheTable
where (BuildingNo, BuildingArea, LocationId) in
(
select BuildingNo, BuildingArea, LocationId
from TheTable
group by BuildingNo, BuildingArea, LocationId
having count(*) > 1
);
What database system do you use? This works in Oracle. It should work in other dbms, too.
Assuming you have a primary key that auto-increments in SQL Server (i.e. set an identify seed), you can write the following query to identify the earliest record in the database for which there is more than one record with identical building, size and location data:
SELECT building, size, location, MIN(ID)
FROM LoadedTableData
GROUP BY building size, location
HAVING COUNT(*) > 1
Correspondingly, you could delete these rows as follows:
DELETE FROM LoadedTableData
WHERE ID IN (
SELECT MIN(ID) as MIN_ID
FROM LoadedTableData
GROUP BY building size, location
HAVING COUNT(*) > 1
)

How to write an SQL query to get records based on the order they were entered in?(no date col) [duplicate]

This question already has answers here:
Is there a "Default Order By Column" in SQL Server?
(2 answers)
How to SELECT the last 10 rows of an SQL table which has no ID field?
(13 answers)
Closed 9 years ago.
I need to write a SQL query that returns records in the order in which they were entered in to a table.
I can't add a column to the table or change the table in any way. I can insert into and select from the table.
Say I execute three insert queries like
insert into x values(a,1);
insert into x values(d,4);
insert into x values(u,42);
when I select from the table x I need to get the records in this order.
a 1
d 4
u 42
The table has only two columns, both have nothing to do with date.
You can't do it without changing the table in some way.
When you select data from a table the order in which it is returned is non-deterministic on all the sql database engines I know and certainly in MSSQL server 2000+. To get the rows in a defined order you must include an ORDER BY clause and there is nothing you can specify to give the desired order.
Since you cannot change the schema, then this is game over.
Okay, (almost) nothing is impossible. You could periodically analyse the physical database file for changes and decode those into the information you require but, this would likely fail when multiple rows were inserted by one transaction.
I doubt you have the access or the inclination to do that.
You can't. The order returned is not deterministic without an order by clause, and you don't have any thing to order by

query - select data by first inserted [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
select bottom rows in natural order
People imagine that i have this table :
persons
columns of the table are NAME and ID
and i insert this
insert into persons values ('name','id');
insert into persons values ('John','1');
insert into persons values ('Jack','3');
insert into persons values ('Alice','2');
How can i select this information order by the insertion? My query would like :
NAME ID
name id
John 1
Jack 3
Alice 2
Without indexs (autoincrements), it's possible?
I'm pretty sure its not. From my knowldege sql data order is not sequetional with respect to insertion. The only idea I have is along with each insertion have a timestamp and sort by that time stamp
This is not possible without adding a column or table containing a timestamp. You could add a timestamp column or create another table containing IDs and a timestamp and insert in to that at the same time.
You cannot have any assumptions about how the DBMS will store data and retrieve them without specifying order by clause. I.e. PostgreSQL uses MVCC and if you update any row, physically a new copy of a row will be created at the end of a table datafile. Using a plain select causes pg to use sequence scan scenario - it means that the last updated row will be returned as the last one.
I have to agree with the other answers, Without a specific field/column todo this... well its a unreliable way... While i have not actually ever had a table without an index before i think..
you will need something to index it by, You can go with many other approaches and methods... For example, you use some form of concat/join of strings and then split/separate the query results later.
--EDIT--
For what reason do you wish not to use these methods? time/autoinc
Without storing some sort of order information during insert, the database does not automatically keep track of every record ever inserted and their order (this is probably a good thing ;) ). Autoincrement cannot be avoided... even with timestamp, they can hold same value.