How to join a column from another table to a new table you wish to display - sql

I am currently working on a database where I am trying to find all the transactional type tables (where the table name does not start with _Result or _ History) in the database and then display how many times each table is used in a calculation for the database model.
The purpose of finding out this is to determine the most important tables in the calculation, so that these certain tables will have a priority when updating statistics.
There are currently two tables I am working with.
1) The first table called tmpCalcSources shows the name for all the source tables in the database (Column called 'Source') along with the Calculation ID (Column called 'CalculationID') associated with it
2) The second table called tmpCalcSourceRows shows the source table name (Column called 'TableName') as well as the amount of rows associated with each source table (Column called 'RowNum')
I currently have this query:
SELECT Source,
COUNT(CalculationID) AS NumberOfUses
FROM tmpCalcSources
WHERE Source not like '%_Result%'
GROUP BY Source
ORDER BY NumberOfUses DESC;
The above query provides me with the following table:
plPeriods 292
plMeasures 10
Time 43
etc...
I am now trying to add one more thing to the above table. I want it to also show the number of rows contained in each table (so a another column). I would like to take the column 'RowNum' from tmpCalcSourceRows table and be able to display that in the table shown above.

Is this what you're looking for:
select
Source
, NumberOfUses
, numberofrows
from (
SELECT Source,COUNT(CalculationID) AS NumberOfUses
FROM tmpCalcSources
WHERE Source not like '%_Result%'
GROUP BY Source
) tableUses
join numRowsTable on numRowsTable.TableName=tableUses.Source
ORDER BY NumberOfUses DESC;

Related

Append data from one table to another table

I have a Destination table with 3 columns, ID, Name, Source.
I have 10+ Source tables, each with multiple columns, but I only require the ID, Name, and the table name itself to be appended into Destination table.
Do note the naming of the column names are different in each table, but the required ID and Name are of the same data type and are of sufficient length for the ID and Name fields.
I already have the query to add the data (see below), and I have no issues doing the first run to add the required data into the destination table, as I just need one query for each table, Here is one my code below
INSERT INTO dest_table
SELECT ID, Name, 'source_table' as Source
FROM source_table
The issue now is that I need to schedule this to run on a daily basis.
I would like the source tables to append their new data into the destination table, and not add all records from each source table into the destination table.
Another condition to consider is that I will still need the data from the destination table to be intact. This means what ever records that were removed from the source tables , will not be removed from the destination table.
Thanks people!
You can exclude the old data by using a WHERE clause as shown below. I am assuming that the ID is unique in this table among all tables else you need to add another column in the destination table to identify where this ID is coming from
INSERT INTO dest_table
SELECT ID, Name, 'source_table' as Source FROM source_table
WHERE NOT EXISTS (SELECT 1 FROM dest_table dt WHERE dt.id = source_table.id)
Another non-optimal approach would be to create a trigger on insert in the source tables and push the data to the destination table.

Copy specific columns from one table to another table, and include the source tablename

I have this newly created table in SQL Server with 3 columns ID, Name, Source.
Basically this table will be populated with data from other different tables, each specifically taking in their record IDs and record Names. I believe this can be easily achieved with an INSERT INTO SELECT statement.
I would like to find out on how to populate the Source column. This column is supposed to indicate which table the data came from. For example, Source in table A has 3 records, which I then copied the ID and Name columns from this table, and put it into my destination table.
At the same time, the 3 new records will have their Source column set, indicating it came from Table A. Then I will proceed to do the same for other tables.
You can use the constant string as follows:
INSERT INTO your_table
SELECT id, name, 'TableA' as source
FROM tableA

Create Select distinct query with criteria of having the latest date

I have been struggling with creating a query in Access to select a distinct field with the criteria of having the newest entry in the database.
Heres a brief summary of how what my table conssists of. I have a table with surveying data collected from 2007 to the present. We have field with a survey marks name with corresponding adjustment data. In the corresponding data there is field with the adjusmtent date. Many of the marks have been occupied mutiple times and only want to retrieve the most recent occupation information.
Roughly i want to
SELECT DISTINCT STATUS_POINT_DESIGNATION
FROM __ALL_ADJUSTMENTS
WHERE [__ALL_ADJUSMENTS]![ADJ_DATE]=MAX(ADJ_DATE)
I seem to be getting confused how relate the select a distinct value with a constraint. Any Suggestions?
DH
Seems you could achieve your aim of getting the latest observation for each survey point by a summary function:
SELECT STATUS_POINT_DESIGNATION, Max(ADJ_DATE) AS LatestDate, Count(STATUS_POINT_DESIGNATION) AS Observations
FROM __ALL_ADJUSTMENTS
GROUP BY STATUS_POINT_DESIGNATION;

How to order the resulting query information being inserting into a table while leaving existing table records on top?

I am trying to insert values from a table into another existing table and have just the values I am inserting be sorted in descending order based on a specific column while leaving the existing records at the top of the table. How do I do that? I have tried to use an Order By statement but whether I use the column name of the table I'm pulling from or the destination table's column name I get an error. Also this is being run in VBA using DoCmd.RunSQL.
Here is my existing query:
INSERT INTO AllMetersAvgRSSI
(longitude,latitude,AvgRSSI)
Select
Prem.longitude, Prem.latitude,
DataByColl.[Avg RSSI]
From [Prem]
Left
Join DataByColl ON (Prem.meter_miu_id
= DataByColl.[MIU ID])
Order BY [AvgRSSI] desc
Final Result
I continued to fiddle with this and discovered than you can use an order by just like I have shown above to do exactly as I was trying to do. The problem I was apparently having was caused by the names of the column I wanted sorted being changed only from Avg RSSI to AvgRSSI. When I changed the destination table to have the same field name as the source table it orders the incoming information while leaving the existing information alone. I also did a test where I changed the name of the destination table to AverageRSSI and it worked the same way. So in the end it was the names of the fields being differed only by a space that was causing the problem. The final Query is:
INSERT INTO AllMetersAvgRSSI
(longitude,latitude,[Avg RSSI])
Select
Prem.longitude, Prem.latitude,
DataByColl.[Avg RSSI]
From [Prem]
Left
Join DataByColl ON (Prem.meter_miu_id
= DataByColl.[MIU ID])
Order BY [Avg RSSI] desc
Ordering in an INSERT makes no sense from a database standpoint. How the database puts the rows into a table depends on the underlying physical structure of the table, not the order in which they are inserted.
Maybe your application relies on an auto incrementing column being in a certain order which would then be dependent on the order of insertion, but if that's the case then I would say that you've made a mistake in your database design as there shouldn't be business logic designed around an auto incrementing column.
Remove the ORDER BY from your INSERT statement and if you need to retrieve rows in a particular order later then use an ORDER BY there.
Create a temp table, add the first result set in the desired order. Insert your new values into the table, query the table to return your new results with an order by into your temp table, select your temp table the results will be in the order you added them unless you do another order by.
Don't forget to drop your temp table after displaying the results.

Need SQL to shift entries from one table to another

Heres the situation. I have 2 tables here of the schema:
ID | COMPANY_NAME | DESC | CONTACT
ID | COMPANY_ID | X_COORDINATE | Y_COORDINATE
The first tabel contains a list of companies and the second contacts coordinates of the companies as mentioned.
The thing is that I want to merge the data in this table with the data in another set of tables which already have data. The other tables have similar structure but are already propopulated with data. The IDs are autoincremental.
SO if we have lets say companies marked 1-1000 in table1 and companies marked 1-500 in table 2. We need it merged such that ID number 1 in table 2 becomes ID 1001 when migrated to the other table. And side by side we would also want to migrated the entries in the coordinates table as well in such a way that they map with the new ids of the table. Can this be done in SQL or do I need to resort to using a script here for this kind of work.
i`m not sure i understand how many tables are there and who is table 1 ,2, but the problem is pretty clear. i think the easy way is:
back up all your database before you start this process
add a column to the destination table that will contain the original id.
insert all the records you want to merge (source) into the destination table, putting the original id in the column you added.
now you can update the geo X,Y data using the old ID
after all is done and good you can remove the original id column.
EDIT: in reply to your comment , i`ll add teh code here, since its more readable.
adapted from SQL Books Online: insert rows from another table
INSERT INTO MyNewTable (TheOriginalID, Desc)
SELECT ID, Desc
FROM OldTable;
Then you can do an update to the new table based on values from the old table like so:
UPDATE MyNewTable SET X = oldTable.X , Y = oldTable.Y where
FROM MYNewTable inner JOIN OldTable ON MYNewTable.TheOriginalID = OldTable.ID