My goal is to retrieve a result of the name of column based on similiar column from table Product_A and Product_B.
It doesn't matter if I gain the result in excel, notepad or table from sql server. The most important is to retrieve the result.
I don't know how to retrieve the result based on calculation with low usage of manual work?
Some criteria you need to take account to:
The column must have the same datatype and name to be similiar
I'm not interrested in retrieving the data from the column
The table is created in a basic level. In reality, the table use 200 column.
The table is in SQL server 2008 R2
TABLE Product_A
(
ProductID INT,
ProductName VARCHAR(100),
Rate MONEY,
Action INT,
MapINT,
)
TABLE Product_B
(
ProductID INT,
Count INT,
ProductName VARCHAR(100),
Rate MONEY
)
Requested result
ProductID INT,
ProductName VARCHAR(100),
Rate MONEY,
This query will compare two tables and return only same-named columns of same datatype. If you need to find all matches accross database, comment out t1.name = condition.
select
t1.name TableName,
c1.name ColumnName,
types.name,
c1.max_length,
c1.precision,
c1.scale
from sys.columns c1
inner join sys.columns c2
-- Condition to join columns - same name, type, length, precision and scale
on c1.name = c2.name
and c1.system_type_id = c2.system_type_id
and c1.max_length = c2.max_length
and c1.precision = c2.precision
and c1.scale = c2.scale
-- Exclude template table
and c1.object_id <> c2.object_id
inner join sys.tables t1
on c1.object_id = t1.object_id
inner join sys.types
on c1.system_type_id = types.system_type_id
inner join sys.tables t2
on c2.object_id = t2.object_id
where t2.name = 'Product_B'
-- remove if you want to search for matches in all tables
and t1.name = 'Product_A'
Check the documentation on sys.columns and sys.tables.
Your requirements are not very clear but you might be referring to a UNION so you can get data from both tables which will give you the product information from each table in separate rows:
SELECT ProductId, ProductName, Rate
FROM Product_A
UNION
SELECT ProductId, ProductName, Rate
FROM Product_B
If you could edit your OP and post some sample data and your expected result then the query could be clarified.
If you know which table you want the data from Table A or B, then you could do a JOIN on the ProductName, but you need to decide which Rate and Product Id you want:
SELECT a.ProductId
, a.ProductName
, a.Rate
FROM Product_A a
JOIN Product_B b
ON a.ProductName = b.ProductName
Related
I have a large list of CustIDs that I need to query on to find if they are within the CUSTOMER table; I want the result to tell me which CustIDs ARE on the table and which CustIDs are NOT on the table.
I provided a short list below to give an idea of what I need to do.
Oracle database
Table: Customer
Primary Key: CustID
Scenario:
Customer table only has the following (2) CustID: ‘12345’, ‘56789’
Sql:
Select * from CUSTOMERS where CUSTID in (‘12345’, ‘56789’, ‘01234’);
I want the result to tell me that both ‘12345’ and ‘56789’ are in the table, AND that ‘01234’ is NOT.
select
v.CustID,
exists (select * from Customer where Customer.CustID = v.CustID)
from (values (12345), (56789), (01234)) v (CustID);
Results:
custid exists
12345 true
56789 true
1234 false
You need a left join or subquery for this. The precise syntax varies by database. Typical syntax is:
select i.custid,
(case when c.custid is not null then 1 else 0 end) as exists_flag
from (select '12345' as custid union all
select '56789' union all
select '01234'
) ci left join
customers c
on c.cust = i.custid;
How I can insert in same row for example I want to insert all these columns data in first row then second and so on. But my query is inserting data when customer name data is complete, status data is inserted after one row of customer number last data.
CREATE TABLE #tblCustomer
(
CustomerNumber NVARCHAR(1000),
Status NVARCHAR (1000),
CustomerType NVARCHAR (1000)
)
INSERT
INTO #tblCustomer (CustomerNumber)
Select c.CustomerNumber
From Customer.Customer c
INSERT
INTO #tblCustomer (Status)
Select ses.Name
From Customer.Customer c
Left Outer Join COM.StatusEngine_EntityStatus sees
On c.Status = sees.EntityStatusId
And sees.EntityId = 'CustomerStatus'
Join COM.StatusEngine_Status ses
On sees.Status = ses.Status
INSERT
INTO #tblCustomer (CustomerType)
select t.Description
From Customer.Customer c
Join Customer.Type t
On c.TypeId = t.pkTypeId
Receiving output:
0001 null null
0002 null null
NULL active null
NULL active null
NULL null individual
NULL null individual
Expected Output:
0001 active individual
0002 active individual
Without knowing more about your tables, you can insert the first records like so...
INSERT INTO #tblCustomer (CustomerNumber)
select c.CustomerNumber from Customer.Customer c
And then update the remaining columns this way...
UPDATE #tblCustomer
set #tblCustomer.Status = c.Status
from Customer.Customer c
left outer join COM.StatusEngine_EntityStatus sees
on c.Status = sees.EntityStatusId and sees.EntityId = 'CustomerStatus'
join COM.StatusEngine_Status ses
on sees.Status = ses.Status
join #tblCustomer temp
on c.CustomerNumber = temp.CustomerNumber
However doing it like this is really inefficient, you should strive to create an insert that updates all columns in one go.
You can do it like this (I have verified the code with the Northwind sample database from Microsoft - I have chosen that one since you can use it for each SQL server version since SQL 2000):
declare #NumberOfItems int = 10;
CREATE TABLE #tblCustomer (
CustomerNumber NVARCHAR(1000)
,Name NVARCHAR (1000)
,CustomerType NVARCHAR (1000))
insert into #tblCustomer
select CustomerNumber, Name, Status from (select top(#NumberOfItems) ROW_NUMBER() OVER(ORDER BY CustomerID) as No, CustomerID as CustomerNumber from Customers) c
left join (select * from (select top(#NumberOfItems) ROW_NUMBER() OVER(ORDER BY ContactName) as No, ContactName as Name from Customers) q2) j1 on c.No=j1.No
left join (select * from (select top(#NumberOfItems) ROW_NUMBER() OVER(ORDER BY ContactTitle) as No, ContactTitle as Status from Customers) q3) j2 on c.No=j2.No
select * from #tblCustomer
drop table #tblCustomer
It will create a column with numbers from 1 to n for each element you want to import and then it joins it together.
The result of this query is:
Note: While this works, it is not the preferred way to do it, because there is no primary key - normally one would look for primary key / foreign key relationships to join the data together. The way you're intending to fill it puts data together which doesn't necessarily belong together (here each column is sorted and then put together by its row number - i.e. it picks values from rows sorted by its extract column and then putting them together again). If you have no primary key because you're importing data from other sources, you can add WHERE clauses to create a better connection between the inner and the outer select statements - you can find a nice article which might help you with such kind of subqueries here.
This is untested, however, I believe this is what you're after:
INSERT INTO #tblCustomer (CustomerNumber, [Status], CustomerType))
SELECT c.CustomerNumber, ses.[Name], t.[Description]
FROM Customer.Customer c
JOIN COM.StatusEngine_EntityStatus sees ON c.Status = sees.EntityStatusId --Changed to JOIN, as it is turned into a implicit INNER join by the next JOIN
AND sees.EntityId = 'CustomerStatus'
JOIN COM.StatusEngine_Status ses ON sees.[Status] = ses.[Status];
Note my comment regarding your LEFT OUTER JOIN, in that I've changed it to an INNER JOIN.
straight forward SQL here:
CREATE TABLE #tblCustomer
(
CustomerNumber NVARCHAR(1000),
Status NVARCHAR (1000),
CustomerType NVARCHAR (1000)
)
INSERT INTO #tblCustomer (CustomerNumber, Status, CustomerType)
SELECT DISTINCT
c.CustomerNumber,
ses.Name,
t.Description
FROM Customer.Customer c
LEFT OUTER JOIN COM.StatusEngine_EntityStatus sees
On c.Status = sees.EntityStatusId
And sees.EntityId = 'CustomerStatus'
LEFT OUTER JOIN COM.StatusEngine_Status ses
On sees.Status = ses.Status
LEFT OUTER JOIN Customer.Type t
On c.TypeId = t.pkTypeId
I am implementing accounting software.
In calculating the balance sheet of the hierarchical self-referenced topics, please let me know the fastest algorithm
These are my tables:
Topics table:
TopicID nvarchar(50) -- is Parent Field
ParentID nvarchar(50) -- is Child Field
Description nvarchar(512)
------------DocumentDetal table
DocumentNumber nvarchar(50)
TopicFK nvarchar(50)
Debit decimal(18,0)
Credit decimal(18,0)
Two tables are related with TopicID and TopicFK columns, please let me know how I can calculate balance sheet using a SQL stored procedure.
Followin are data samples:
Following are Documents:
Actually I want following calculation results:
For your SQL Server 2008 R2, Here is for sumDebit and sumCredit. Don't understand how to calculate Res Debit and Res credit but I think you could edit to get your Res value too.
Anyway, this is using CTE thank to Mikael Eriksson in Recursive sum in tree structure
with T as
(
select t.TopicID, t.ParentID, sum(d.Debit) as sumDebit, sum(d.Credit) as sumCredit
from Topics t
left join DocumentDetail d
on t.TopicID = d.TopicFK
group by t.TopicID, t.ParentID
)
,C as
(
select T.TopicID,
T.sumDebit,
T.sumCredit,
T.TopicID as RootID
from T
union all
select T.TopicID,
T.sumDebit,
T.sumCredit,
C.RootID
from T
inner join C
on T.ParentId = C.TopicID
)
select T.TopicID,
T.ParentId,
S.sumDebitIncludingChildren sumDebit,
S.sumCreditIncludingChildren sumCredit
from T
inner join (
select RootID,
sum(sumDebit) as sumDebitIncludingChildren,
sum(sumCredit) as sumCreditIncludingChildren
from C
group by RootID
) as S
on T.TopicID = S.RootID
order by T.TopicID
option (maxrecursion 0);
Tested OK in SQL Fiddle
I'm sure this is answered elsewhere, however I'm not sure how to search for this specific question.
Let's say I have 2 tables:
InputDataNames with columns [Prospect_Name], [Product_Name], [Market_Name]
Entity with columns [EntityId], [Name], [EntityTypeId], where [Name] is used in the InputDataNames table.
Now suppose I want to create a table equal to InputDataNames, but instead of Names, fill in with IDs from the Entity table:
InputDataIDs with columns [Prospect_ID], [Product_ID], [Market_ID]
Using the InputDataNames table to populate the appropriate combination of IDs, how can I join with the Entity table to get the desired effect?
Note: I know this is sloppy, just doing a little database cleanup.
You can join to the entity table three times. Assuming the EntityTypeId column determines whether or not the entity is a prospect, product, or market, then you should include that column in the join. If they are numbered 1,2,3:
select
pros.entityid, prod.entityid, mkt.entityid
from
inputdatanames id
inner join
entity pros on id.prospect_name = pros.name and pros.entitytypeid = 1
inner join
entity prod on id.product_name = prod.name and prod.entitytypeid = 2
inner join
entity mkt on id.market_name = mkt.name and mkt.entitytypeid = 3
insert InputDataIDs
(Prospect_ID, Product_ID, Market_ID)
select Prospect.EntityID
, Product.EntityID
, Market.EntityID
from InputDataNames
left join
Entity Prospect
on Prospect.EntityTypeId = 1 -- Type of prospect
and Prospect.Name = InputDataNames.Prospect_Name
left join
Entity Product
on Product.EntityTypeId = 2 -- Type of product
and Product.Name = InputDataNames.Product_Name
left join
Entity Market
on Market.EntityTypeId = 3 -- Type of market
and Market.Name = InputDataNames.Market_Name
There are three fields in a table, all of them refer the same field in another table, like this:
table1
-------
! a_term_id* ! b_term_id* ! c_term_id* !
! ! ! !
table2
-------
! term_id ! term_title ! term_description !
! ------- ! ! !
columns a_term_id, b_term_id, c_term_id all refer to term_id
How should I write the SQL statement to retrieve the three fields' info?
I think you need to know how Sql_Join works. Here on W3Schools you can find useful examples.
A simple example:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
EDIT
You can try something like this:
SELECT * FROM tableA
inner join tableB on tableA.term_id = tableB.term_id
inner join tableC on tableA.term_id = tableC.term_id;
It an example you can modify as per your need.
Edit 2
SELECT * FROM tableB
JOIN tableA AS tableA1 ON tableB.term_id = tableA1.a_term_id
JOIN tableA AS tableA2 ON tableB.term_id = tableA2.b_term_id
JOIN tableA AS tableA3 ON tableB.term_id = tableA3.c_term_id
Here is an example. Suppose that we have two tables - Employees and Companies:
CREATE TABLE Employees(
Id int,
Name varchar(128),
CompanyId int);
CREATE TABLE Companies(
Id int,
Name varchar(128),
Address varchar(1024),
DateFounded datetime);
The following SQL query will join the tables:
SELECT * FROM Employees
INNER JOIN Companies
ON Employees.CompanyId = Companies.Id
Your question is a bit unclear, but I'll guess that you have a table A with three fields, each of which identifies a (possibly different) row from table B. You want to retrieve info from each of those rows of table B based on the field values of a single row of table A.
To do this, you will need to join table A to table B three times, once for each field of table A. Each join should be given an alias and then you can refer to the fields in the joined table by qualified field names.
SELECT b1.info, b2.info, b3.info
FROM A JOIN B AS b1 ON field1 = b1.field
JOIN B AS b2 ON field2 = b2.field
JOIN B AS b3 ON field3 = b2.field
WHERE ...
SELECT
t.a_term_id, a.term_title, a.term_description,
t.b_term_id, b.term_title, b.term_description,
t.c_term_id, c.term_title, c.term_description
FROM abc_terms t JOIN ( terms_info a, terms_info b, terms_info c )
ON ( t.a_term_id = a.term_id
AND t.b_term_id = b.term_id
AND t.c_term_id = c.term_id )