Union on muliple tables in C# - c#

I am using C# and trying to do union on multiple datatables in the code.
Table 1
ID | Value | Value2
-----------------
1 | Tom | Null
-----------------
2 | John | Null
-----------------
...
Table 2
ID | Value | Value2
-----------------
1 | Null | Susie
-----------------
2 | Null | Kim
-----------------
...
And, I want the result table would be something like
TableResult
ID | Value | Value2
-----------------
1 | Tom | Susie
-----------------
2 | John | Kim
-----------------
...
Is there a way I could this?

I'm not sure what datastructure you are using in C#, but you can do this right in your database:
SELECT COALESCE(Table1.ID, Table2.ID) AS ID
,COALESCE(Table1.Value, Table2.Value) AS Value
,COALESCE(Table1.Value2, Table2.Value2) AS Value2
FROM Table1
FULL OUTER JOIN Table2
ON Table1.ID = Table2.ID
I chose a FULL OUTER JOIN here so that items could be missing on EITHER side (I generally expect most people will use a FULL OUTER JOIN about once a year in their careers), as well as an arbitrary choice to always pick the value in Table1 if it existed first, so Table2 would not overwrite something in Table1.
So as an example of how the FOJ works:
Table 1
1,A,NULL
2,B,X
3,NULL,Y
4,D,Z
Table 2
1,NULL,P
2,NULL,Q
3,C,NULL
5,E,W
Output:
1,A,P
2,B,X
3,C,Y
4,D,Z
5,E,W

If they're already in DataTables, you could load them into another table:
DataTable unionTable = new DataTable();
unionTable.Load(table1.CreateDataReader());
unionTable.Load(table2.CreateDataReader());
I think the notion of doing it server side as previously mentioned is a lot better approach though...

Another way to do this in Linq
//Lets say you have two tables (fill the variables from dababase)
IQueryable tab1 = new List().AsQueryable();
IQueryable tab2 = new List().AsQueryable();
//You can create Result table this way
var resultTable = tab1.Select(t1 => new Table1 { t1.ID, t1.Value, tab2.Any(t2 => t2.ID == t1.ID) ? tab2.First(t2 => t2.ID == t1.ID).Value : null });

Related

Data insertion into the hierarchy format from one table to another

I have an issue in insertion of records from one table to another the tables schema is same
Table 1
Id Parent Id Text
11 Null A
12 Null B
13 11 C
14 11 D
15 13 E
The record should be inserted in this format, I have to copy the foreign key relation not the identities of it.
Table 2
Id Parent Id Text
31 Null A
32 Null B
33 31 C
34 31 D
35 33 E
What you want could be achieved easily in the Database side.
But since you are looking for a linq approach. Here is how it can be achieved.
The Process is divided into two parts:
Hoping that you would have the model for the Table1 and Table2 something like(use the order you think is helpful. For my thinking the Table1 is the temp table):
Public class myEntity
{
public int Id{get; set;}
public int? ParentId{get; set;}
public string Text{get; set;}
}
1st: Copying all the Text Properties from Table A and inserting them into Table B with incrementing the IDs
var Table2 = new List<myEntity>();
Table1.Select(s=>s.Text).OrderBy(o=>o).ToList().ForEach(f=>
{
//now append the texts to
Table2.Add(new tablesTest { Id = (Table2.Count + 1), Text = f });//remove the Id property manupulation or set it to 0 if you are inserting directly in the database and use the context.SaveChanges();(*if entity-framework*) once the insertion is complete.
}}
2nd: Creating a mapping table using self-join to get the parent-child relationship between the entries from Table1 and then updating the entries in Table2
var parentChildListFromTb1 = from m in Table1
join ch in Table1 on m.Id equals ch.ParentId
select new
{
Id = ch.Id,
Parent = m.Text,
Text = ch.Text
};
Which will give you an output:
----------------------------
| Id | Parent | Text |
----------------------------
| 13 | A | C |
----------------------------
| 14 | A | D |
----------------------------
| 15 | C | E |
----------------------------
Now after we have the parent-child list now we create the child list by querying Table2 and updating its ParentId with their respected Ids:
parentChildListFromTb1.ForEach(f=>{
var ChildEntity = Table2.Single(s => s.Text.Equals(f.Text));//fetching the child entity from Table2
ChildEntity.ParentId = Table2.Single(s => s.Text.Equals(f.Parent)).Id;//updating the parentIds in Table2
});
And the Table2 will look something like :
------------------------------
| Id | ParentId | Text |
------------------------------
| 1 | null | A |
------------------------------
| 2 | null | B |
------------------------------
| 3 | 1 | C |
------------------------------
| 4 | 1 | D |
------------------------------
| 5 | 3 | E |
------------------------------
I have found a solution to this question.
Steps:
Insert the Text column values into the main table, leaving the ParentId as null and at the same time insert the values into a Dictionary as oldId key and New Inserted Id as value to the corresponding key.
After insertion Update the values on the basis of the mapped Dictionary keyValue Pair

Entity ORM Joining Two Tables Off ID ForeignKey given non-foreignkey?

I have a string, name.
I have two tables:
Table 1:
|---------------------|------------------|
| ID | PadName |
|---------------------|------------------|
| 12 | "Hello" |
|---------------------|------------------|
Table 2
|------------------------------------------|------------------|
| MetaDataID (FK to ID in table1) | .......... |
|------------------------------------------|------------------|
| 12 | Other Data..
|------------------------------------------|------------------|
Example Query:
Select ID from table1 given a padName the join that ID with table2.
I'm using entity framework in C# and what I want is to feed in a PadName in Table 1 and then get all the associated Table 2 data where the ID fields match (since table2 has an FK relationship to table 1).
I've seen some example code like the following:
var query = _context.PadMetaData
.Where(x => x.PadName == padName).Select(p => new { p.id });
Then I want to take that id result and join it with the MetaDataId in table2.
But I can't seem to achieve what I want.

Updating a Table column based on the value of another table which are not related in SQL Server 2008

I have two tables which are not directly related, like...
Table 1
VoucherId | VoucherDate
-----------+-------------
V001 | 2014-12-09
V002 | 2016-01-10
Table 2
FinYearRef | FromDate | ToDate
-----------+------------+-----------
Y01 | 2014-07-01 | 2015-06-30
Y02 | 2015-07-01 | 2016-06-30
Now I add a column FRef to Table 1
I want to update that FRef column by FinYearRef from Table 2 where Table1.VoucherDate is between Table2.FromDate and Table2.ToDate
Update with Join:
UPDATE T1
SET T1.FRef = T2.FinYearRef
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.VoucherDate BETWEEN T2.FromDate AND T2.ToDate
Note that this will update FRef with the last match from T2. If you want the first value then:
UPDATE TABLE1
SET T1.FRef =
(SELECT TOP 1 FinYearRef FROM TABLE2
WHERE TABLE1.VoucherDate BETWEEN T2.FromDate AND T2.ToDate)

Join two tables where second table is used as a reference for multiple columns of the first table

I have two tables (names are fictitious for this example):
---------------------------------------
MainTable
---------------------------------------
Condition_1 | Condition_2 | Condition_3
---------------------------------------
J | H | N
R | T |
I | |
W | T |
R | M | Q
...and so on...
--------------------------------------
Conditions
--------------------------------------
Condition_Code | Condition_Description
--------------------------------------
A | Description goes here
B | Description goes here
C | Description goes here
D | Description goes here
E | Description goes here
F | Description goes here
G | Description goes here
...and so on...
I'd like to be able to query a DataSet that would have the Condition_Description from the Conditions table as the value of each condition that has a code within the MainTable table.
So that when I look at a specific row:
ds.Tables["Query"].Rows[i]["Condition_1"].ToString();
I would either get an empty string or a description of that condition, if it previously contained a code.
So that for the first row in the above example, it would return the full description of J instead of the character value.
I tried this query:
SELECT * FROM MainTable
LEFT JOIN Conditions AS C1 ON
MainTable.Condition_1 = C1.Condition_Code
LEFT JOIN Conditions AS C2 ON
MainTable.Condition_2 = C2.Condition_Code
LEFT JOIN Conditions AS C3 ON
MainTable.Condition_3 = C3.Condition_Code
...however, I get a missing operator in query expression error.
P.S. It was tough to create the title for this one, since my database experience is limited, so if anyone has a better title, feel free to change it.
If I understood you correctly than maybe something like this would do the trick:
SELECT
(
SELECT FIRST(Condition_Description) FROM Conditions C1 WHERE MT.Condition_1 = C1.Condition_Code
) as C1_Description,
(
SELECT FIRST(Condition_Description) FROM Conditions C2 WHERE MT.Condition_2 = C2.Condition_Code
) as C2_Description,
(
SELECT FIRST(Condition_Description) FROM Conditions C3 WHERE MT.Condition_3 = C3.Condition_Code
) as C3_Description
FROM MainTable as MT
P.s. Not sure what is syntax of first function in access. Also Conditions table design is not very elegant :)

Querying a database or a datatable for duplicate records in one column

On MS access, how to get the "ID" of the records having duplicate content on the "myData" column ?
something like :
---------------------- ------------------------
ID | myData | | ID | myData |
---------------------- ------------------------
1 | AAA | | 1 | AAA |
---------------------- ------------------------
2 | BBB | | 5 | AAA |
---------------------- ==> ------------------------
3 | CCC | | 2 | BBB |
---------------------- ------------------------
4 | BBB | | 4 | BBB |
---------------------- ------------------------
5 | AAA |
----------------------
All I can do so far do is this query:
SELECT myData, COUNT(myData) AS Expr1
FROM fooDB
GROUP BY myData
HAVING (COUNT(myData) > 1)
which only returns a list of the duplicates records from "mydata" and the number of occurrences, adding anything else will fail at execute. (and no ID's)
OR
Saying I accessing the DB as a DataTable in C#, how to manage this? Especially when this table has ~2000 records.
( maybe some help on how to work with INTERSECT to let it return the full rows having duplicates on one column )
Thanks.
SELECT ID, fooDB.myData
FROM (
SELECT myData
FROM fooDB
GROUP BY myData
HAVING COUNT(myData) > 1
) t INNER JOIN fooDB ON (t.myData = fooDB.myData)
I don't know if you can do a subquery in Access like this, but here's a typical SQL way to do it:
SELECT
id,
my_data
FROM
My_Table
WHERE
my_data IN
(
SELECT
my_data
FROM
My_Table
GROUP BY
my_data
HAVING
COUNT(*) > 1
)
Just throwing this out there...
SELECT distinct
f.ID,
f.myData
FROM
fooDB f
inner join fooDB f2 on f.myData = f2.myData
and f.ID <> f2.ID
Try
SELECT ID
FROM fooDB
WHERE myData IN (SELECT myData
FROM (SELECT myData, COUNT(myData) AS ROW_COUNT
FROM fooDB
GROUP BY myData)
WHERE ROW_COUNT > 1)
Share and enjoy.

Categories

Resources