I have a query where I send a TableType who have columns EmpKey and TaskId like:
#AssignNotificationTableType [dbo].[udf_TaskNotification] READONLY
INSERT INTO [TaskNotification] ([TaskId], [EmpKey])
SELECT
[ANT].[TaskId], [E].[EmpKey]
FROM
#AssignNotificationTableType AS [ANT]
INNER JOIN
[Employee] AS [E] ON [ANT].[EmpGuid] = [E].[EmpGuid]
So my table looks like this:
+--------------------------------------+--------------------------------------+--------+
| TaskNotificationId | TaskId | EmpKey |
+--------------------------------------+--------------------------------------+--------+
| EEE3D3F8-F190-E811-841F-C81F66DACA6A | D0440DEB-404C-4006-870F-E95BFFA840E0 | 44 |
| EFE3D3F8-F190-E811-841F-C81F66DACA6A | D0440DEB-404C-4006-870F-E95BFFA840E0 | 49 |
+--------------------------------------+--------------------------------------+--------+
As you can see two items have same TaskId but different Empkey, so suppose if I send again same TaskId D0440DEB-404C-4006-870F-E95BFFA840E0 I want to insert only row only if EmpKey does not exist in that TaskId
So if I send something like:
+--+--------------------------------------+--------+
| | TaskId | EmpKey |
+--+--------------------------------------+--------+
| | D0440DEB-404C-4006-870F-E95BFFA840E0 | 44 |
| | D0440DEB-404C-4006-870F-E95BFFA840E0 | 49 |
| | D0440DEB-404C-4006-870F-E95BFFA840E0 | 54 |
+--+--------------------------------------+--------+
It will only insert last row, because EmpKey 54 does not exist in that TaskId
I try to do in WHERE clause with NOT IN as:
INSERT INTO [TaskNotification] ([TaskId], [EmpKey])
SELECT
[ANT].[TaskId], [E].[EmpKey]
FROM
#AssignNotificationTableType AS [ANT]
INNER JOIN
[Employee] AS [E] ON [ANT].[EmpGuid] = [E].[EmpGuid]
WHERE
[E].[EmpKey] NOT IN (SELECT EmpKey
FROM [TaskNotification]
WHERE TaskId = (SELECT TaskId
FROM #AssignNotificationTableType))
But when I run it, it just don't insert anything. What am I doing wrong? Regards
Add the target table as a left join to the select statement:
INSERT INTO [TaskNotification]
(
[TaskId]
, [EmpKey]
)
SELECT
[ANT].[TaskId]
, [E].[EmpKey]
FROM #AssignNotificationTableType AS [ANT]
INNER JOIN [Employee] AS [E] ON [ANT].[EmpGuid] = [E].[EmpGuid]
LEFT JOIN [TaskNotification] AS [TN] ON [TN].[TaskId] = [ANT].[TaskId]
AND [TN].[EmpKey] = [E].[EmpKey]
WHERE [TN].[PK] IS NULL -- PK stands for the primary key column
-- (or first column in of a multiple columns pk)
Please note, however, this in a multithreaded environment such query might fail - For more information, read this SO post and Dan Guzman's blog post it links to.
Related
In my PostgreSQL database I have a table like this one:
id|link1|link2|
---------------
1 | 34 | 66
2 | 23 | 8
3 | 11 | 99
link1 and link2 fields are both pointing to the same table table2 which has id and descr fields.
I would make an SQL query that returns the same row the id and the descr value for the two field like this:
id|link1|link2|desc_l1|desc_l2|
-------------------------------
1 | 34 |66 | bla | sisusj|
2 | 23 | 8 | ghhj | yui |
3 | 11 | 99 | erd | bnbn |
I've try different queries, but everyone returns two rows per id instead of one.
How can I achieve these results in my PostgreSQL 9.04 database?
Normally, this query should work for you. Assume your first table name's table_name.
SELECT t.id, t.link1, t.link2,
l1.descr AS desc_l1,
l2.descr AS desc_l2
FROM table_name t
LEFT JOIN table2 l1
ON t.link1 = l1.id
LEFT JOIN table2 l2
ON t.link2 = l2.id;
you can use case here Like:
select link1,link2,
case
when link1='34' and link2='66' then 'bla'
when link1='23' and link2='8' then 'ghs'
when link1='11' and link2='99' then 'erd'
end as desc_li,
case
when link1='34' and link2='66' then 'sjm'
when link1='23' and link2='8' then 'yur'
when link1='11' and link2='99' then 'bnn'
end as desc_l2
from table1
I have the following table
CREATE TABLE Topic_details(
topicid BIGINT NOT NULL PRIMARY KEY IDENTITY(1,1)
,parent_topicid BIGINT
,description NVARCHAR(184) NOT NULL
,code NVARCHAR(43) NOT NULL
,lang_id INT
,entryby INT NOT NULL
,enrtydate DATE NOT NULL
,last_updateby INT
,last_update_date DATE
);
Now insert some sample data into it
INSERT INTO Topic_details(topicid,parent_topicid,description,code,lang_id,entryby,enrtydate,last_updateby,last_update_date)
VALUES
(1,NULL,N'Overview of C',N'Overview of C',NULL,10238,'2017-06-10 13:09:52.297',NULL,NULL)
,(2,1,N'Features of C',N'Features of C',NULL,10238,'2017-06-10 13:10:09.060',NULL,NULL)
,(3,1,N'C Language Applications',N'C Language Applications',NULL,10238,'2017-06-10 13:13:13.607',NULL,NULL)
,(4,1,N'C Program Execution',N'C Program Execution',NULL,10238,'2017-06-10 13:13:32.623',NULL,NULL)
,(5,1,N'What is Interpreter ?',N'What is Interpreter ?',NULL,10238,'2017-06-10 13:14:17.897',NULL,NULL)
Now in my application there is a requirement to insert these kind of data from excel.
Now the sheet that user will be uploaded consists three columns
ParentTopicName|TopicName|Code|
---------------|---------|----|
and let have some sample data into it,
ParentTopicName|TopicName|Code|
---------------|---------|----|
|Joins |Join|
----------------|---------|----|
Joins | Inner J | IJ |
-------------------------------|
Joins | Left J | LJ |
Now I have a datatable which will store excel's data.
Now, In procedure
Create ROCEDURE [dbo].[sp_upload_topic_subtopic]
#entry_by bigint = null,
#lang_id nvarchar(20) = null,
#dtTopicSubtopic ttTopicSubtopic ReadOnly -- to store value from datatable
AS
BEGIN
INSERT INTO dbo.topic_details([description], code,entryby,enrtydate,lang_id)
SELECT d.TopicName, d.TopicCode,#entry_by,Getdate(),1 from #dtTopicSubtopic as d
UPDATE td
SET td.parent_topicid= ptd.topicid
FROM dbo.topic_details td
INNER JOIN #dtTopicSubtopic d ON d.TopicName=td.[description]
INNER JOIN topic_details ptd ON d.ParentTopic=ptd.[description]
END
This will store data as expected in Topic_Details table
After storing into table,
---------------------------------------------------
Topic_Details
---------------------------------------------------
TopicId |ParentTopiID|desciption|Code|.....
---------------|------------|----------|----|.....
1 | NULL | Joins |Join|.....
---------------|------------|----------|----|.....
2 | 1 | Inner J | IJ |.....
---------------|------------|----------|----|.....
3 | inserted data..................
--------------|------------------------------------
4 | inserted data...................
--------------|-------------------------------------
Now later suppose I am inserting another row from excel. (please note Inner j is already present in my table and I'm inserting Inner J again.)
ParentTopicName|TopicName |Code|
---------------|--------- |----|
|Inner J |Ij |
----------------|--------- |----|
Inner J |Some Thing| dj |
This will insert data into Topic_details table as follows
TopicId |ParentTopiID|desciption|Code|.....
---------------|------------|----------|----|.....
1 | NULL | Joins |Join|.....
---------------|------------|----------|----|.....
2 | 1 | Inner J | IJ |.....
3......
4......
5 | Null | Inner J | IJ | ....
-------------|-------------|------------|----|-----
6 | 2 | Something|hfdj|......
But as 'Inner J' is already present in my table so,
1. TopicId with 5 will not be inserted. (solved)
2. As 'Something' is the child of 'Inner J' so parentid of 'Something' will be 2 because 'Inner J' is already present in my table.
Final Out Put what I want
------------------------------------------------------
Topic_details
-------------------------------------------------------
TopicId |ParentTopiID|desciption|Code|.....
---------------|------------|----------|----|.....
1 | NULL | Joins |Join|.....
---------------|------------|----------|----|.....
2 | 1 | Inner J | IJ |.....
---------------|------------|----------|-----|
3.....................
4.....................
5.....................
-------------|-------------|------------|----|-----
6 | 2 | Something|hfdj|......
How can I achieve this ?
If I understand your question correctly, you do not want to insert duplicate records.
INSERT INTO dbo.topic_details([description], code,entryby,enrtydate,lang_id)
SELECT d.TopicName, d.TopicCode,#entry_by,Getdate(),1 from #dtTopicSubtopic as d
WHERE NOT EXISTS( SELECT * FROM dbo.topic_details AS Cur WHERE Cur.TopicName = d.TopicName AND Cur.TopicCode = d.TopicCode )
The above code checks if the record with a given TopicName and TopicCode already exists in dbo.topic_details and does not insert it.
Update:
After much confusion, which as it turns out, is due to the fact that OP query already works.
One other Issue I notice is that topicid BIGINT and parent_topicid INTEGER are of different data types. They should use the same as these columns establish a relation and will be frequently joined.
First time posting, please forgive my newbieness!
In MS Access 2013, How can I update the Actions table's 'LatestRequest' column with the 'id' from the IncomingRequests table by using only for the latest RequestDate for each Scan Result ID ?
Note that there can be duplicate Scan Result IDs in IncomingRequests, but the date will always be different.
Actions Table:
id (primary key) | Scan Result ID | LatestRequest | other-misc-columns...
1 | 123456 | (blank)
2 | 666666 | (blank)
3 | 789789 | (blank)
4 | 888888 | (blank) (this record won't change)
5 | 999222 | 987 (this record won't change)
IncomingRequests Table:
id (primary key) | RequestDate | Scan Result ID | other-misc-columns...
201 | 5/9/2016 | 123456
202 | 4/12/2016 | 123456
203 | 5/7/2016 | 666666
204 | 5/8/2016 | 666666
205 | 5/9/2016 | 789789
What I want to see:
Action Table:
id (primary key) | Scan Result ID | LatestRequest | other-misc-columns...
1 | 123456 | 201
2 | 666666 | 204
3 | 789789 | 205
4 | 888888 | (blank)
5 | 999222 | 987
I've tried creating a subquery for the max date, and updating the Actions table, but run into "Operation must use an updateable query".
UPDATE Actions INNER JOIN (SELECT t1.*
FROM
IncomingRequests t1
INNER JOIN
(
SELECT [Scan Result ID], MAX([DateFromIT]) AS MaxDate
FROM IncomingRequests
GROUP BY [Scan Result ID]
) t2
ON t1.[Scan Result ID]=t2.[Scan Result ID]
AND t1.[RequestDate]=t2.MaxDate
) AS ij ON Actions.[Scan Result ID] = ij.[Scan Result ID]
SET LatestRequest = ij.id
The alternate version I have (below) checks using the Request table primary key id, and this works, except that I really need it by latest date, not highest id.
UPDATE Actions
INNER JOIN IncomingRequests ON Actions.[Scan Result ID] = IncomingRequests.[Scan Result ID]
SET Actions.latestrequest = IncomingRequests.id
WHERE IncomingRequests.id=
(SELECT MAX(IncomingRequests.id)
FROM IncomingRequests
WHERE Actions.[Scan Result ID] = IncomingRequests.[Scan Result ID]
GROUP BY IncomingRequests.[Scan Result ID] );
I've ran into many dead ends trying to follow other answers from this site, or errors in MS Access that others didn't seem to get. Any assistance appreciated.
Thanks so much! =)
Try this and let me know if this solved your problem
update Actions set Actions.LatestRequest = t2.id
from Actions
inner join (select id,ScanResultID from IncomingRequests where RequestDate
in (select MAX(RequestDate) from IncomingRequests group by ScanResultID))
t2 on Actions.ScanResultID = t2.ScanResultID
I eventually resolved by creating a Sub module in VBA to do the following:
DROP a temp table.
Perform a SELECT with the MAX date into a temp table.
Perform an UPDATE with an INNER JOIN to the temp table.
DROP the temp table.
Ugly, but it's the only way I could get it to work.
A brief explanation on the relevant domain part:
A Category is composed of four data:
Gender (Male/Female)
Age Division (Mighty Mite to Master)
Belt Color (White to Black)
Weight Division (Rooster to Heavy)
So, Male Adult Black Rooster forms one category. Some combinations may not exist, such as mighty mite black belt.
An Athlete fights Athletes of the same Category, and if he classifies, he fights Athletes of different Weight Divisions (but of the same Gender, Age and Belt).
To the modeling. I have a Category table, already populated with all combinations that exists in the domain.
CREATE TABLE Category (
[Id] [int] IDENTITY(1,1) NOT NULL,
[AgeDivision_Id] [int] NULL,
[Gender] [int] NULL,
[BeltColor] [int] NULL,
[WeightDivision] [int] NULL
)
A CategorySet and a CategorySet_Category, which forms a many to many relationship with Category.
CREATE TABLE CategorySet (
[Id] [int] IDENTITY(1,1) NOT NULL,
[Championship_Id] [int] NOT NULL,
)
CREATE TABLE CategorySet_Category (
[CategorySet_Id] [int] NOT NULL,
[Category_Id] [int] NOT NULL
)
Given the following result set:
| Options_Id | Championship_Id | AgeDivision_Id | BeltColor | Gender | WeightDivision |
|------------|-----------------|----------------|-----------|--------|----------------|
1. | 2963 | 422 | 15 | 7 | 0 | 0 |
2. | 2963 | 422 | 15 | 7 | 0 | 1 |
3. | 2963 | 422 | 15 | 7 | 0 | 2 |
4. | 2963 | 422 | 15 | 7 | 0 | 3 |
5. | 2964 | 422 | 15 | 8 | 0 | 0 |
6. | 2964 | 422 | 15 | 8 | 0 | 1 |
7. | 2964 | 422 | 15 | 8 | 0 | 2 |
8. | 2964 | 422 | 15 | 8 | 0 | 3 |
Because athletes may fight two CategorySets, I need CategorySet and CategorySet_Category to be populated in two different ways (it can be two queries):
One Category_Set for each row, with one CategorySet_Category pointing to the corresponding Category.
One Category_Set that groups all WeightDivisions in one CategorySet in the same AgeDivision_Id, BeltColor, Gender. In this example, only BeltColor varies.
So the final result would have a total of 10 CategorySet rows:
| Id | Championship_Id |
|----|-----------------|
| 1 | 422 |
| 2 | 422 |
| 3 | 422 |
| 4 | 422 |
| 5 | 422 |
| 6 | 422 |
| 7 | 422 |
| 8 | 422 |
| 9 | 422 | /* groups different Weight Division for BeltColor 7 */
| 10 | 422 | /* groups different Weight Division for BeltColor 8 */
And CategorySet_Category would have 16 rows:
| CategorySet_Id | Category_Id |
|----------------|-------------|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 7 | 7 |
| 8 | 8 |
| 9 | 1 | /* groups different Weight Division for BeltColor 7 */
| 9 | 2 | /* groups different Weight Division for BeltColor 7 */
| 9 | 3 | /* groups different Weight Division for BeltColor 7 */
| 9 | 4 | /* groups different Weight Division for BeltColor 7 */
| 10 | 5 | /* groups different Weight Division for BeltColor 8 */
| 10 | 6 | /* groups different Weight Division for BeltColor 8 */
| 10 | 7 | /* groups different Weight Division for BeltColor 8 */
| 10 | 8 | /* groups different Weight Division for BeltColor 8 */
I have no idea how to insert into CategorySet, grab it's generated Id, then use it to insert into CategorySet_Category
I hope I've made my intentions clear.
I've also created a SQLFiddle.
Edit 1: I commented in Jacek's answer that this would run only once, but this is false. It will run a couple of times a week. I have the option to run as SQL Command from C# or a stored procedure. Performance is not crucial.
Edit 2: Jacek suggested using SCOPE_IDENTITY to return the Id. Problem is, SCOPE_IDENTITY returns only the last inserted Id, and I insert more than one row in CategorySet.
Edit 3: Answer to #FutbolFan who asked how the FakeResultSet is retrieved.
It is a table CategoriesOption (Id, Price_Id, MaxAthletesByTeam)
And tables CategoriesOptionBeltColor, CategoriesOptionAgeDivision, CategoriesOptionWeightDivison, CategoriesOptionGender. Those four tables are basically the same (Id, CategoriesOption_Id, Value).
The query look like this:
SELECT * FROM CategoriesOption co
LEFT JOIN CategoriesOptionAgeDivision ON
CategoriesOptionAgeDivision.CategoriesOption_Id = co.Id
LEFT JOIN CategoriesOptionBeltColor ON
CategoriesOptionBeltColor.CategoriesOption_Id = co.Id
LEFT JOIN CategoriesOptionGender ON
CategoriesOptionGender.CategoriesOption_Id = co.Id
LEFT JOIN CategoriesOptionWeightDivision ON
CategoriesOptionWeightDivision.CategoriesOption_Id = co.Id
The solution described here will work correctly in multi-user environment and when destination tables CategorySet and CategorySet_Category are not empty.
I used schema and sample data from your SQL Fiddle.
First part is straight-forward
(ab)use MERGE with OUTPUT clause.
MERGE can INSERT, UPDATE and DELETE rows. In our case we need only to INSERT. 1=0 is always false, so the NOT MATCHED BY TARGET part is always executed. In general, there could be other branches, see docs. WHEN MATCHED is usually used to UPDATE; WHEN NOT MATCHED BY SOURCE is usually used to DELETE, but we don't need them here.
This convoluted form of MERGE is equivalent to simple INSERT, but unlike simple INSERT its OUTPUT clause allows to refer to the columns that we need.
MERGE INTO CategorySet
USING
(
SELECT
FakeResultSet.Championship_Id
,FakeResultSet.Price_Id
,FakeResultSet.MaxAthletesByTeam
,Category.Id AS Category_Id
FROM
FakeResultSet
INNER JOIN Category ON
Category.AgeDivision_Id = FakeResultSet.AgeDivision_Id AND
Category.Gender = FakeResultSet.Gender AND
Category.BeltColor = FakeResultSet.BeltColor AND
Category.WeightDivision = FakeResultSet.WeightDivision
) AS Src
ON 1 = 0
WHEN NOT MATCHED BY TARGET THEN
INSERT
(Championship_Id
,Price_Id
,MaxAthletesByTeam)
VALUES
(Src.Championship_Id
,Src.Price_Id
,Src.MaxAthletesByTeam)
OUTPUT inserted.id AS CategorySet_Id, Src.Category_Id
INTO CategorySet_Category (CategorySet_Id, Category_Id)
;
FakeResultSet is joined with Category to get Category.id for each row of FakeResultSet. It is assumed that Category has unique combinations of AgeDivision_Id, Gender, BeltColor, WeightDivision.
In OUTPUT clause we need columns from both source and destination tables. The OUTPUT clause in simple INSERT statement doesn't provide them, so we use MERGE here that does.
The MERGE query above would insert 8 rows into CategorySet and insert 8 rows into CategorySet_Category using generated IDs.
Second part
needs temporary table. I'll use a table variable to store generated IDs.
DECLARE #T TABLE (
CategorySet_Id int
,AgeDivision_Id int
,Gender int
,BeltColor int);
We need to remember the generated CategorySet_Id together with the combination of AgeDivision_Id, Gender, BeltColor that caused it.
MERGE INTO CategorySet
USING
(
SELECT
FakeResultSet.Championship_Id
,FakeResultSet.Price_Id
,FakeResultSet.MaxAthletesByTeam
,FakeResultSet.AgeDivision_Id
,FakeResultSet.Gender
,FakeResultSet.BeltColor
FROM
FakeResultSet
GROUP BY
FakeResultSet.Championship_Id
,FakeResultSet.Price_Id
,FakeResultSet.MaxAthletesByTeam
,FakeResultSet.AgeDivision_Id
,FakeResultSet.Gender
,FakeResultSet.BeltColor
) AS Src
ON 1 = 0
WHEN NOT MATCHED BY TARGET THEN
INSERT
(Championship_Id
,Price_Id
,MaxAthletesByTeam)
VALUES
(Src.Championship_Id
,Src.Price_Id
,Src.MaxAthletesByTeam)
OUTPUT
inserted.id AS CategorySet_Id
,Src.AgeDivision_Id
,Src.Gender
,Src.BeltColor
INTO #T(CategorySet_Id, AgeDivision_Id, Gender, BeltColor)
;
The MERGE above would group FakeResultSet as needed and insert 2 rows into CategorySet and 2 rows into #T.
Then join #T with Category to get Category.IDs:
INSERT INTO CategorySet_Category (CategorySet_Id, Category_Id)
SELECT
TT.CategorySet_Id
,Category.Id AS Category_Id
FROM
#T AS TT
INNER JOIN Category ON
Category.AgeDivision_Id = TT.AgeDivision_Id AND
Category.Gender = TT.Gender AND
Category.BeltColor = TT.BeltColor
;
This will insert 8 rows into CategorySet_Category.
Here is not the full answer, but direction which you can use to solve this:
1st query:
select row_number() over(order by t, Id) as n, Championship_Id
from (
select distinct 0 as t, b.Id, a.Championship_Id
from FakeResultSet as a
inner join
Category as b
on
a.AgeDivision_Id=b.AgeDivision_Id and
a.Gender=b.Gender and
a.BeltColor=b.BeltColor and
a.WeightDivision=b.WeightDivision
union all
select distinct 1, BeltColor, Championship_Id
from FakeResultSet
) as q
2nd query:
select q2.CategorySet_Id, c.Id as Category_Id from (
select row_number() over(order by t, Id) as CategorySet_Id, Id, BeltColor
from (
select distinct 0 as t, b.Id, null as BeltColor
from FakeResultSet as a
inner join
Category as b
on
a.AgeDivision_Id=b.AgeDivision_Id and
a.Gender=b.Gender and
a.BeltColor=b.BeltColor and
a.WeightDivision=b.WeightDivision
union all
select distinct 1, BeltColor, BeltColor
from FakeResultSet
) as q
) as q2
inner join
Category as c
on
(q2.BeltColor is null and q2.Id=c.Id)
OR
(q2.BeltColor = c.BeltColor)
of course this will work only for empty CategorySet and CategorySet_Category tables, but you can use select coalese(max(Id), 0) from CategorySet to get current number and add it to row_number, thus you will get real ID which will be inserted into CategorySet row for second query
What I do when I run into these situations is to create one or many temporary tables with row_number() over clauses giving me identities on the temporary tables. Then I check for the existence of each record in the actual tables, and if they exist update the temporary table with the actual record ids. Finally I run a while exists loop on the temporary table records missing the actual id and insert them one at a time, after the insert I update the temporary table record with the actual ids. This lets you work through all the data in a controlled manner.
##IDENTITY is your friend to the 2nd part of question
https://msdn.microsoft.com/en-us/library/ms187342.aspx
and
Best way to get identity of inserted row?
Some API (drivers) returns int from update() function, i.e. ID if it is "insert". What API/environment do You use?
I don't understand 1st problem. You should not insert identity column.
Below query will give final result For CategorySet rows:
SELECT
ROW_NUMBER () OVER (PARTITION BY Championship_Id ORDER BY Championship_Id) RNK,
Championship_Id
FROM
(
SELECT
Championship_Id
,BeltColor
FROM #FakeResultSet
UNION ALL
SELECT
Championship_Id,BeltColor
FROM #FakeResultSet
GROUP BY Championship_Id,BeltColor
)BASE
I have been searching around for how to do this for days - unfortunately I don't have much experience with SQL Queries, so it's been a bit of trial and error.
Basically, I have created two tables - both with one DateTime column and a different column with values in.
The DateTime column has different values in each table.
So...
ACOQ1 (Table 1)
===============
| DateTime | ACOQ1_Pump_Running |
|----------+--------------------|
| 7:14:12 | 1 |
| 8:09:03 | 1 |
ACOQ2 (Table 2)
===============
| DateTime | ACOQ2_Pump_Running |
|----------+--------------------|
| 3:54:20 | 1 |
| 7:32:57 | 1 |
I want to combine these two tables to look like this:
| DateTime | ACOQ1_Pump_Running | ACOQ2_Pump_Running |
|----------+--------------------+--------------------|
| 3:54:20 | 0 OR NULL | 1 |
| 7:14:12 | 1 | 0 OR NULL |
| 7:32:57 | 0 OR NULL | 1 |
| 8:09:03 | 1 | 0 OR NULL |
I have achieved this by creating a third table that 'UNION's the DateTime column from both tables and then uses that third table's DateTime column for the new table but was wondering if there was a way to skip this step out.
(Eventually I will be adding more and more columns on from different tables and don't really want to be adding yet more processing time by creating a joint DateTime table that may not be necessary).
My working code at the moment:
CREATE TABLE JointDateTime
(
DateTime CHAR(50)
CONSTRAINT [pk_Key3] PRIMARY KEY (DateTime)
);
INSERT INTO JointDateTime (DateTime)
SELECT ACOQ1.DateTime FROM ACOQ1
UNION
SELECT ACOQ2.DateTime FROM ACOQ2
SELECT JointDateTime.DateTime, ACOQ1.ACOQ1_NO_1_PUMP_RUNNING, ACOQ2.ACOQ2_NO_1_PUMP_RUNNING
FROM (SELECT ACOQ1.DateTime FROM ACOQ1
UNION
SELECT ACOQ2.DateTime FROM ACOQ2) JointDateTime
LEFT OUTER JOIN ACOQ1
ON JointDateTime.DateTime = ACOQ1.DateTime
LEFT OUTER JOIN ACOQ2
ON JointDateTime.DateTime = ACOQ2.DateTime
You need a plain old FULL OUTER JOIN like this.
SELECT COALESCE(A1.DateTime,A2.DateTime) DateTime,ACOQ1_Pump_Running, ACOQ2_Pump_Running
FROM ACOQ1 A1
FULL OUTER JOIN ACOQ2 A2
ON A1.DateTime = A2.DateTime
This will give you NULL for ACOQ1_Pump_Running, ACOQ2_Pump_Running for rows which do not match the date in the corresponding table. If you need 0 just use COALESCE or ISNULL.
Side Note: : In your script, I can see your are using DateTime CHAR(50). Please use appropriate types