Create column with values based on join - sql

I have two tables 1) a customer table 2)Account table. I want to see what accounts are primary and which are secondary accounts.
In one table I have accountRowId. In the other table I have PrimaryAccountRowId and SecondaryAccountRowId and ‘AccountNumber’.
For my output I would like to have all AccountNumbers in one column with all the AccountRelationship(primary or seconday) in another column beside each AccountNumber.
In order to join table, for PrimaryAccounts I would join AccountRowId on PrimaryAccountRowId and for secondary Accounts I would just flip flop and instead of having the primaryAccountRowId it would be SecondaryAccountRowId.
My Account table:
AccountRowId = 256073
AccountRowId = 342300
Customer table:
PrimaryAccountRowId = 256073
SecondaryAccountRowId = 342300
AccountNumber = 8003564
AccountNumber = 2034666
What I want to see my table look like
AccoundNumber AccountRelationship
8003564 Primary
2034666 Secondary
Please provide some helpful logic/code of how I would achieve these results.
From the OP's comments here is the table structure.
Create table Customer
(
AccountNumber Varchar(50)
, PrimaryAccountRowId Varchar(15)
, SecondaryAccountRowId Varchar(15)
);
Create table Account
(
AccountRowId Varchar(15)
);

I am still somewhat guessing here. You need to provide table structure, sample data and desired output to make it easy for people to help you. Something along these lines.
declare #Customer table
(
AccountNumber Varchar(50)
, PrimaryAccountRowId Varchar(15)
, SecondaryAccountRowId Varchar(15)
)
insert #Customer values
('8003564', '256073', null)
, ('2034666', null, '342300')
declare #Account table
(
AccountRowid Varchar(15)
)
INSERT #Account values
('256073'), ('342300')
Now that we have some tables and data to work with this just becomes a case of conditional aggregation. This should return the data you are looking for as I understand the need.
select c.AccountNumber
, AccountRelationship = max(case when p.AccountRowId is not null then 'Primary' when c.SecondaryAccountRowId is not null then 'Secondary' end)
from #Customer c
left join #Account p on p.AccountRowid = c.PrimaryAccountRowId
left join #Account s on s.AccountRowid = c.SecondaryAccountRowId
group by c.AccountNumber
order by AccountRelationship

Related

How to split data in SQL Server table row

I have table of transaction which contains a column transactionId that has values like |H000021|B1|.
I need to make a join with table Category which has a column CategoryID with values like H000021.
I cannot apply join unless data is same.
So I want to split or remove the unnecessary data contained in TransctionId so that I can join both tables.
Kindly help me with the solutions.
Create a computed column with the code only.
Initial scenario:
create table Transactions
(
transactionId varchar(12) primary key,
whatever varchar(100)
)
create table Category
(
transactionId varchar(7) primary key,
name varchar(100)
)
insert into Transactions
select'|H000021|B1|', 'Anything'
insert into Category
select 'H000021', 'A category'
Add computed column:
alter table Transactions add transactionId_code as substring(transactionid, 2, 7) persisted
Join using the new computed column:
select *
from Transactions t
inner join Category c on t.transactionId_code = c.transactionId
Get a straighforward query plan:
You should fix your data so the columns are the same. But sometimes we are stuck with other people's bad design decisions. In particular, the transaction data should contain a column for the category -- even if the category is part of the id.
In any case:
select . . .
from transaction t join
category c
on transactionid like '|' + categoryid + |%';
Or if the category id is always 7 characters:
select . . .
from transaction t join
category c
on categoryid = substring(transactionid, 2, 7)
You can do this using query :
CREATE TABLE #MyTable
(PrimaryKey int PRIMARY KEY,
KeyTransacFull varchar(50)
);
GO
CREATE TABLE #MyTransaction
(PrimaryKey int PRIMARY KEY,
KeyTransac varchar(50)
);
GO
INSERT INTO #MyTable
SELECT 1, '|H000021|B1|'
INSERT INTO #MyTable
SELECT 2, '|H000021|B1|'
INSERT INTO #MyTransaction
SELECT 1, 'H000021'
SELECT * FROM #MyTable
SELECT * FROM #MyTransaction
SELECT *
FROM #MyTable
JOIN #MyTransaction ON KeyTransacFull LIKE '|'+KeyTransac+'|%'
DROP TABLE #MyTable
DROP TABLE #MyTransaction

How can I pull data from multiple sql tables using a join statement

I'm designing a simple in-office ticket system, and would like to include a field for the party responsible for the next action. To do so right this moment I'm thinking of using tableName and tableID as specifiers for the specific responsible party (could be a technician, customer, or third party, all in different tables)
It would be fine to pull that data in and run another select call using the name of the table as a parameter, but the extra data flow slows things down significantly.
Is there a way to use a single join statement to return the details of the party with a column for the table name and one for the individual table id or is there a better way to store the data from multiple potential tables?
You can use left join to achieve your requirement :-
Set Nocount On;
Declare #OfficeTickets Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,PartyType Varchar(1)
,TechnicianId Int Null
,CustomerId Int Null
,ThirdPartyId Int Null
)
Declare #OfficeTickets1 Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,TableName Varchar(100)
,TableId Int Null
)
Declare #Technician Table
(
Id Int Identity(1,1)
,TechnicianName Varchar(100)
)
Declare #Customers Table
(
Id Int Identity(1,1)
,CustomerName Varchar(100)
)
Declare #ThirdParty Table
(
Id Int Identity(1,1)
,ThirdPartyName Varchar(100)
)
Insert Into #Technician(TechnicianName) Values
('Technician_1')
,('Technician_2')
,('Technician_3')
Insert Into #Customers(CustomerName) Values
('Customer_1')
,('Customer_2')
,('Customer_3')
Insert Into #ThirdParty(ThirdPartyName) Values
('ThirdParty_1')
,('ThirdParty_2')
,('ThirdParty_3')
,('ThirdParty_4')
Insert Into #OfficeTickets(Column1,PartyType,TechnicianId,CustomerId,ThirdPartyId) Values
('ABC','T',3,Null,Null)
,('XYZ','C',Null,2,Null)
,('PUQ','P',Null,Null,4)
Insert Into #OfficeTickets1(Column1,TableName,TableId) Values
('ABC','Technician',3)
,('XYZ','Customers',2)
,('PUQ','ThirdParty',4)
---- taken separate columns for parties
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From #OfficeTickets As ot
Left Join #Technician As t On ot.PartyType = 'T' And ot.TechnicianId = t.Id
Left Join #Customers As c On ot.PartyType = 'C' And ot.CustomerId = c.Id
Left Join #ThirdParty As tp On ot.PartyType = 'P' And ot.ThirdPartyId = tp.Id
---- by TableName and TableId
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From #OfficeTickets1 As ot
Left Join #Technician As t On ot.TableName = 'Technician' And ot.TableId = t.Id
Left Join #Customers As c On ot.TableName = 'Customers' And ot.TableId = c.Id
Left Join #ThirdParty As tp On ot.TableName = 'ThirdParty' And ot.TableId = tp.Id
output:-

SSIS populating cross reference table

Destination tables look like this:
Source table look like this:
Customer
CustomerId FirstName LastName Email Address1 Address2 City Zip
Person table in destination is a base table (which will later be inherited by new customer table). So I am trying to export a row from one table and populate 3 tables in destination.
I managed to do this in following way:
Get records from source table (Customer)
Create empty AddressId field
Populate Address table using OLE DB Command task (it calls stored procedure which returns SCOPE_IDENTITY() that's mapped to AddressId field)
Repeat step 3 for populating Person table (and retrieving PersonId
Populate cross reference table PersonAddress using PersonId and AddressId fields
Screenshot of this package is below.
Biggest issue with this approach is that OLE DB Command task is inserting row by row and it makes the whole package extremely slow. Is it possible to achieve the same thing but using fast load?
I am able to do it using OLE DB Command task which calls the stored procedure and then
I don't think you need SSIS.
You can use OUTPUT clause of INSERT which returns all identity keys to a temporary table
Lets try reproduce your scenario...
set nocount on
go
create table Customer (CustomerId int, CustomerName varchar(100) null, Address1 varchar(100) null, Address2 varchar(100) )
create table [Person] (PersonId int identity, PersonName varchar(100) null)
create table [Address] (AddressId int identity, AddressLine varchar(100) null)
create table [PersonAddress] (AddressId int, PersonId int )
go
-- create some data...
insert into Customer (CustomerId) values ( 1000000 + convert(int, RAND() * 1000000) )
go 1000
update Customer
set CustomerName = 'CustomerName ' + convert(varchar, CustomerId),
Address1 = 'Address1 ' + convert(varchar, CustomerId),
Address2 = 'Address2 ' + convert(varchar, CustomerId)
go
declare #identities_Person table ([rownumber] int identity, id int)
declare #identities_Address table ([rownumber] int identity, id int)
insert into Person (PersonName)
output inserted.PersonId into #identities_Person
select
c.CustomerName
from Customer c
order by c.CustomerId
insert into [Address] (AddressLine)
output inserted.AddressId into #identities_Address
select
c.Address1
from Customer c
order by c.CustomerId
insert into [PersonAddress] (PersonId, AddressId)
select p.id, a.id
from #identities_Address a
inner join #identities_Person p on p.rownumber = a.rownumber
select *
from PersonAddress pa
inner join [Address] a on a.AddressId = pa.AddressId
inner join [Person] p on p.PersonId = pa.PersonId

How to use equal and not equal together in SQL Server

I have to select values from three tables. First table is sale_project_detail, the second table is design_project_detail, and the third table is design_designer.
sale_project_detail schema:
Id int,
Name nvarchar(50),
ShortDescription nvarchar(max)
design_project_assignment schema:
Id int,
DId int (It is foreign key of design_designer table),
SPId int (It is foreign key of sale_project_detail table),
AssignDateTime datetime,
DueDate date,
Status varchar(10)
design_designer schema:
Id int,
Name nvarchar(15)
Now, I have to select complete detail from sale_project_detail
where assign_project_detail.SPId <> sale_project_detail.Id,
and
Select design_designer(Name)
from design_designer
where design_designer.Id = assign_project_detail.DId
I am trying below code, but it is returning wrong result.
My code:
SELECT
sale_project_detail.*,
design_project_assignment.*,
design_designer.Name
FROM
sale_project_detail,
design_project_assignment,
design_designer
WHERE
NOT EXISTS(SELECT NULL
FROM design_project_assignment
LEFT JOIN design_designer ON design_designer.Id = design_project_assignment.DId
WHERE sale_project_detail.Id = design_project_assignment.SPId)
Thanks in advance.
Try this
SELECT
*
FROM
sale_project_detail as spd
inner join design_project_assignment dpa on dpa.spid <> spd.id
inner join design_designer dd on dd.id = dpa.did;

SQL Server - copy data from staging table

I am using staging tables to perform validation and insert into live.
Suppose I have a table PERSONS
TABLE Persons
(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
HouseNumber int,
)
and a STAGING TABLE as follows
TABLE Persons_Staging
(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
HouseNumber varchar(255),
)
I need to write a procedure to transfer data from the staging table to the live table while ensuring no duplicates are inserted. How can I achieve that?
Thanks in advance
Use the MERGE command.
Something like this:
MERGE
INTO Persons AS TARGET
USING Persons_Staging AS SOURCE
ON TARGET.ID = SOURCE.ID
--WHEN MATCHED
-- THEN UPDATE???
WHEN NOT MATCHED BY TARGET
THEN INSERT (Id , LastName , FirstName, HouseNumber)
VALUES (SOURCE.Id , SOURCE.LastName , SOURCE.FirstName, SOURCE.HouseNumber)
-- WHEN NOT MATCHED BY SOURCE
-- THEN DELETE???
;
If you want to update existing records you uncomment the UPDATE part and add a suitable update clause. The same with the delete part.
you could use this with a left outer join on both tables to get all the data that isn't the same. That data you then can insert into your column
INSERT INTO Tab1(front,end,number)
SELECT first,last,nr from tab2 LEFT OUTER JOIN tab1 ON front = first AND last = end AND convert(int,number) = CONVERT(int,nr)
WHERE tab1.ID is null
this could work, on the other hand there are tools made for this kind of stuff