I have this table that hold several products
And another table that holds the order for each product from above
How can i combine these tables and get the sum of each ord_Count per item and show it as another column, like this
To summarize it, I have a Items table that holds different products, and an Orders table that holds the orders for each product from the Items Table, then I want to have a query that combines both tables and show a my stock for each item from the Items table.
Try this:
SELECT SUM(ord_count) AS Item_stock, itm_Code
FROM YourTable
GROUP BY itm_Code
To combine both table:
SELECT SUM(B.ord_count) AS Item_stock, B.itm_Code
FROM YourTable1 AS A
INNER JOIN YourTable2 AS B
ON A.itm_Code = B.itm_Code
GROUP BY B.itm_Code
declare #t table (item varchar(20),itemcode varchar(20))
insert into #t (item,itemcode)values ('choco','ckschoc'),('chocowafer','wfrchoc'),('chocostrrae','wfrstr')
declare #tt table (ordcnt int,itemcode varchar(20),dated date)
insert into #tt (ordcnt,itemcode,dated)values (20,'ckschoc','4/24/2015'),(10,'wfrchoc','4/24/2015'),(15,'wfrstr','4/24/2015')
,(30,'ckschoc','4/24/2015'),(20,'wfrstr','4/24/2015')
we can achieve the same result using sub query and corelated join query also
Solution
select t.itemcode,p.S from #t t INNER JOIN (
select itemcode,SUM(ordcnt)S from #tt
GROUP BY itemcode)P
ON p.itemcode = t.itemcode
group by t.itemcode,P.s
select t.itemcode,
(select SUM(tt.ordcnt)Cnt from #tt tt
where tt.itemcode = t.itemcode
group by tt.itemcode )Cnt from #t t
Related
I have 2 tables which have 2 columns in common and 1 column is different in both table
Table A
Table B
I need to create a common table having the values as follows
Expected Output
I tried using join on Memid and Meas but it duplicates as the 2 field do not create unique set as shown in figure
I tried union but then I get a resultset like this
Output for Inner join with distinct condition
How do I go about achieving the desired result set?
Note: Just a note coincidentally in this case the 2 columns seems to have similar values but they can be different.
Basically I need to create this one table with the 4 columns where Payer and PPayer columns should be independent of each other.
You don't need to use UNION, you can try like following using INNER JOIN.
INSERT INTO NewTable (
UserId
,DEPT
,ROOM
,LAB
)
SELECT DISTINCT ta.UserId
,ta.DEPT
,ta.ROOM
,tb.LAB
FROM TableA ta
INNER JOIN TableB tb ON ta.UserId = tb.UserId
AND ta.DEPT = tb.DEPT
Check Working Demo
Shanawaz Khan, Try this Solution
Declare Sample Table
DECLARE #A as TABLE(
UserId INT,
DEPT VARCHAR(50),
ROOM INT)
DECLARE #B as TABLE(
UserId INT,
DEPT VARCHAR(50),
LAB VARCHAR(50))
Insert Sample Records in Created Table
INSERT INTO #A (UserId,DEPT,ROOM) VALUES(1,'A',1),(1,'B',1),(1,'A',2),(1,'B',2)
INSERT INTO #B (UserId,DEPT,LAB) VALUES(1,'A','P'),(1,'B','Q'),(1,'A','P'),(1,'B','Q')
Generate DEPT wise Row number for Both Tables and Insert into another Temptable
SELECT ROW_NUMBER() OVER(PARTITION BY A.DEPT ORDER BY A.ROOM ) AS Rno,* INTO #tbl_A FROM #A A
SELECT ROW_NUMBER() OVER(PARTITION BY B.DEPT ORDER BY B.LAB) AS Rno,* INTO #tbl_B FROM #B B
Final Query Using Inner Join
SELECT A.UserId,A.DEPT,A.ROOM,B.LAB FROM #tbl_A AS A
INNER JOIN #tbl_B AS B ON A.Rno =B.Rno AND A.DEPT =B.DEPT ORDER BY A.ROOM, B.DEPT
Drop Created Temptable
DROP TABLE #tbl_A,#tbl_B
OutPut
I want to group several rows of table A and insert a new row into table B for each bunch of grouped rows.
Next to that I want to update the rows of table A with the ID of the newly inserted row.
Inserting the lines into the table with 'grouplines' is like:
INSERT INTO B(...,...,...)
SELECT col1, col2 FROM A
GROUP BY col1,col2
This will produce a list of IDs in table B. I want to update the rows of table A with the ID of the corresponding group-row of table B.
Is there a possibilty to do this?
Some sample data:
After grouping table B looks like:
And then table A should look like:
As it is, your query potentially inserts more than one row.
I think that one solution would to use two queries: first insert in table b from table a, the update table a with newly created id(s) from table b.
INSERT INTO B(col1, col2, col3)
SELECT DISTINCT col1, col2, col3 FROM A
UPDATE A
SET A.B_ID = B.B_ID
FROM A
INNER JOIN B
ON A.col1 = B.col1
AND A.col2 = B.col2
AND A.col3 = B.col3
Deme on db<>fiddle
You can achieve table B by using Row_Number like below
Select ROW_NUMBER() OVER(ORDER BY Category) as ID, Name, Category
into #B
from #A
group by Name, Category
Then Update the table A after joining with table B like
Update a
set a.ID_Of_Group_row = b.ID
from #A a
inner join #B b on a.Category = b.Category
Output
I have record like below in SQL Server.
Id RefId FromRefId
1 RH01 RH00
2 RH02 RH01
3 RH03 RH01
4 RH04 RH03
5 RH05 RH02
6 RH06 RH03
7 RH07 RH04
8 RH08 RH02
9 RH09 RH05
And I want get result like below using Id in where condition
Where Id=1
RH02
RH03
RH04
RH05
RH06
RH07
RH08
RH09
Where Id=2
RH05
RH08
RH09
Where Id=3
RH04
RH06
RH07
Where Id=4
RH07
Where Id=5
RH09
Thanks, please guide me how can I achieve this?
Since you want to obtain all the references following the chain of FromRefId you need to use a recursive query, which can be achieved in SQL Server using a recursive common table expression:
with Recursive_IDs (Id, RefId, FromRefId) as (
-- anchor query
select Id, RefId, FromRefId
from IDs
union all
-- recursive query
select IDs.Id, IDs.RefID, Recursive_IDs.FromRefId
from IDs
inner join Recursive_IDs on Recursive_IDs.RefId=IDs.FromRefId
)
select Recursive_IDs.RefId
from Recursive_IDs
join IDs on Recursive_IDs.FromRefID=IDs.RefID
where IDs.id = [the id you want]
SQL fiddle
Note that if instead of searching by Id you search by RefId you can simplify the query a bit:
with Recursive_IDs (Id, RefId, FromRefId) as (
-- anchor query
select Id, RefId, FromRefId
from IDs
union all
-- recursive query
select IDs.Id, IDs.RefID, Recursive_IDs.FromRefId
from IDs
inner join Recursive_IDs on Recursive_IDs.RefId=IDs.FromRefId
)
select Recursive_IDs.RefId
from Recursive_IDs
where FromRefId = [the RefId you want]
You can use the below approach. I have written a Table-valued function, "GetChild". It iterates through the records recursively to get all dependencies, and finally get the RefId for all those dependencies.
Create table hierarchy (Id int, RefId varchar(10), FromRefId varchar(10))
GO
insert into hierarchy
select 1,'RH01','RH00' union all
select 2,'RH02','RH01' union all
select 3,'RH03','RH01' union all
select 4,'RH04','RH03' union all
select 5,'RH05','RH02' union all
select 6,'RH06','RH03' union all
select 7,'RH07','RH04' union all
select 8,'RH08','RH02' union all
select 9,'RH09','RH05'
GO
-- Table valued Function
GO
create function GetChild (#Id INT)
RETURNS #temp TABLE (RefId varchar(10))
AS
BEGIN
declare #tempDependencies table (Id int)
insert into #tempDependencies SELECT #Id
WHILE ((Select COUNT(Id) from hierarchy where FromRefId in (select RefId from hierarchy where id in (select Id from #tempDependencies) ) and id not in (select Id from #tempDependencies)) > 0)
BEGIN
insert into #tempDependencies
Select Id from hierarchy where FromRefId in (select RefId from hierarchy where id in (select Id from #tempDependencies) ) and id not in (select Id from #tempDependencies)
END
insert into #temp
Select RefId from hierarchy where FromRefId in (select RefId from hierarchy where id in (SELECT Id from #tempDependencies))
return
END
GO
-- You may call the functions like this:
select * from GetChild(1)
select * from GetChild(2)
select * from GetChild(3)
SQL Fiddle Code
Should be a simple query
SELECT * FROM your_table_name WHERE Id = your_desired_id
Why the downgrade? Isn’t that what you were looking for? I don’t think your question is clear. Which Id is being referred here?!
This query is fine works.
SELECT * FROM TABLE WHERE 330110042 IN (iItem01,iItem02,iItem03,iItem04,iItem05,iItem_1,iItem_2,iItem_3,iItem_4,iItem_5,iItem_6,iItem_7,iItem_8,iItem_9,iItem_10,iItem_11,iItem_12,iItem_13,iItem_14,iItem_15,iItem_16,iItem_17,iItem_18,iItem_19,iItem_20,iItem_21,iItem_22,iItem_23,iItem_24,iItem_25,iItem_26,iItem_27,iItem_28,iItem_29,iItem_30)
But this query didnt work.
SELECT * FROM TABLE WHERE 330110042, 330110002, 330110002 IN (iItem01,iItem02,iItem03,iItem04,iItem05,iItem_1,iItem_2,iItem_3,iItem_4,iItem_5,iItem_6,iItem_7,iItem_8,iItem_9,iItem_10,iItem_11,iItem_12,iItem_13,iItem_14,iItem_15,iItem_16,iItem_17,iItem_18,iItem_19,iItem_20,iItem_21,iItem_22,iItem_23,iItem_24,iItem_25,iItem_26,iItem_27,iItem_28,iItem_29,iItem_30)
How i work in SQL Server?
It's difficult to tell your exact goal here, but one possibility would be to turn the list of values into a table structure of its own. A Common Table Expression might work:
;WITH Ids AS
(
SELECT 330110042 AS Id
UNION ALL
SELECT 330110002
)
SELECT t.*
FROM [Table] t
INNER JOIN Ids i ON t.iItem01 = i.Id OR t.iItem02 = i.Id OR...
But, maybe a solution with UNPIVOT would be more elegant. I presume that your table has a primary key column called Id:
;WITH Unpivoted AS
(
SELECT Id, ColName, ColValue
FROM (SELECT Id, iItem01, iItem02, iItem03
FROM [Table] t) p
UNPIVOT
(ColValue FOR ColName IN (iItem01, iItem02, iItem03)) AS unpvt
)
SELECT t.*
FROM [Table] t
WHERE EXISTS (SELECT 1 FROM Unpivoted u
WHERE t.Id = u.Id
AND u.ColValue IN (330110042, 330110002))
Of course, you would add all the necessary columns. I added only the first three for this example.
There is a table called: IDs and another table called Entries.
Not all ids from Ids have entries. I do want to count how many entries have ALL the ids. if an Id has no entry I want to print 0.
Ids have PK: ID and Entries have a column ID.
If I joined them I get only the IDS having entries, but I want to get all of the IDS.
You are using INNER JOIN you can achieve this by using LEFT JOIN instead
EXAMPLE
/* Declare Temperory table for data storage */
DECLARE #MasterTable AS TABLE
(
ID INT
)
DECLARE #EntryTable AS TABLE
(
EntryID INT IDENTITY(1,1)
,MasterId INT
)
--Insert entries to Master Table
INSERT INTO #MasterTable
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
--Insert details into details table for only 1 and 2
INSERT INTO #EntryTable
(
MasterId
)
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 3
SELECT
ID
,COUNT(EntryTable.MasterId) AS EntryCount
FROM
#MasterTable MainTable
LEFT JOIN
#EntryTable EntryTable
ON
MainTable.ID = EntryTable.MasterId
GROUP BY
ID
Use a left join
select ids.id, count(entries.id)
from ids
left join entries on entries.id = ids.id
group by ids.id
Also see this great explanation of joins
SELECT DISTINCT id, EntriesCount.entriesCount
FROM IDs
OUTER APPLY (
SELECT COUNT(id) entriesCount
FROM Entries
WHERE Entries.ids = IDs.id
) AS EntriesCount
outer apply let's you use the id from IDs in the 'where' condition from Entries.