insert data order by from another table - sql-server-2008

I have 2 table first is master table second is transaction table.i want to insert data from second table into temp table .
I need to insert a table data from another table. I trying to write this sql code. But this order by option is not working while inserting the data
insert data from table in order of grant table .but i think it insert fist then order.
here is my table syntax.
Create table tabl_master
(DESC_ID int IDENTITY(1,1) PRIMARY KEY,
SUM_DESCRIPTION nvarchar(500)
)
Create table tabl1
(PROGRESS_REPORT_BUDGETID int IDENTITY(1,1) PRIMARY KEY,
RFP_ID int,
DESC_ID int ,
TOTAL_BUDGET decimal(18,2)
)
insert into tabl_master values('1.1 Salaries-Program management staff')
insert into tabl_master values('1.2 Salaries-Field staff, outreach workers, medical staff and other service providers')
insert into tabl_master values('1.3 Other HR Costs')
insert into tabl_master values('1.4 Salaries-Finance and Administration Staff')
insert into tabl_master values('2.2 Technical Assistance related per diems/transport/other costs')
insert into tabl_master values('2.3 Assistance related per diems/transport/other costs')
insert into tabl1 values(101,1,2500)
insert into tabl1 values(101,2,7500)
insert into tabl1 values(101,3,3500)
insert into tabl1 values(101,4,0)
insert into tabl1 values(101,5,0)
insert into tabl1 values(101,6,0)
insert into tabl1 values(101,7,0)
DECLARE #ProductTotals TABLE
(
srnum int,
PROGRESS_REPORT_BUDGETID int,
SUM_DESCRIPTION nvarchar(550),
RFP_ID int,
DESC_ID int,
GRAND_TOTAL decimal(18,3)
)
insert into #ProductTotals
SELECT row_number() over (order by (select NULL))as srnum,
PROGRESS_REPORT_BUDGETID,BS.SUM_DESCRIPTION,
RFP_ID, PB.DESC_ID, TOTAL_BUDGET
FROM tabl1 PB
INNER JOIN tabl_master BS ON PB.DESC_ID=BS.DESC_ID
ORDER BY TOTAL_BUDGET desc
select * from #ProductTotals
Result is coming as
enter image description here
And i am expecting result as
enter image description here

DECLARE #ProductTotals TABLE
(
srnum int,
PROGRESS_REPORT_BUDGETID int,
SUM_DESCRIPTION nvarchar(550),
RFP_ID int,
DESC_ID int,
GRAND_TOTAL decimal(18,3)
)
insert into #ProductTotals
SELECT row_number() over (order by (select NULL))as srnum,
PROGRESS_REPORT_BUDGETID,SUM_DESCRIPTION,
RFP_ID, DESC_ID, TOTAL_BUDGET from(
SELECT
PROGRESS_REPORT_BUDGETID,BS.SUM_DESCRIPTION,
RFP_ID, PB.DESC_ID, TOTAL_BUDGET
FROM tabl1 PB
INNER JOIN tabl_master BS ON PB.DESC_ID=BS.DESC_ID
where TOTAL_BUDGET <> 0
union all
select PROGRESS_REPORT_BUDGETID,BS.SUM_DESCRIPTION,
RFP_ID, PB.DESC_ID, TOTAL_BUDGET
FROM tabl1 PB
INNER JOIN tabl_master BS ON PB.DESC_ID=BS.DESC_ID
where TOTAL_BUDGET = 0
) A
select * from #ProductTotals
and my expected answer will be like this
enter image description here

Related

How do I insert a limited number records to TableA from TableB , where TableC contains the list of records to insert?

I am using MySQL 5.6
Note:
TableA is Active_Orders
TableB is Old_Orders
TableC is Move_Orders
The field "contract" is unique in all three tables.
Here is what I got so far
Database setup:
CREATE TABLE IF NOT EXISTS Active_Orders (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
contract VARCHAR(255) NOT NULL UNIQUE
) ENGINE=INNODB;
INSERT INTO Active_Orders(name, contract)
VALUES ('steve', '3454'),
('tom', '6756'),
('becky', '9809');
CREATE TABLE IF NOT EXISTS Old_Orders (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
contract VARCHAR(255) NOT NULL UNIQUE
) ENGINE=INNODB;
INSERT INTO Old_Orders(name,contract)
VALUES ('mark', '9896'),
('kelly', '0897'),
('paul', '1537'),
('will', '8254');
CREATE TABLE IF NOT EXISTS Move_Orders (
contract VARCHAR(255) NOT NULL UNIQUE
) ENGINE=INNODB;
INSERT INTO Move_Orders(contract)
VALUES ('0897'),
('1537);
The Code I am using is:
INSERT INTO Active_Orders (name, contract)
SELECT name, contract
FROM Old_Orders
WHERE Move_Orders.contract = Old_Orders.contract;
But I am getting
#1054 - Unknown column 'Move_Orders.contract' in 'where clause'
What I want the result to be is:
SELECT * FROM Active_Orders;
id name contract
1 steve 3454
2 tom 6756
3 becky 9809
4 kelly 0897
5 paul 1537
I understand that 'Move_Orders.contract' is not in the FROM clause so I am getting error, but I am not sure how to rewrite the statement to get the output I need.
INSERT INTO Active_Orders (name, contract)
SELECT Old_Orders.name, Old_Orders.contract
FROM Old_Orders
JOIN Move_Orders ON Move_Orders.contract = Old_Orders.contract;
or
INSERT INTO Active_Orders (name, contract)
SELECT Old_Orders.name, Old_Orders.contract
FROM Old_Orders, Move_Orders
WHERE Move_Orders.contract = Old_Orders.contract;
or
INSERT INTO Active_Orders (name, contract)
SELECT name, contract
FROM Old_Orders
WHERE EXISTS ( SELECT contract
FROM Move_Orders
WHERE Move_Orders.contract = Old_Orders.contract )
It's nearly a literal translation from English:
INSERT INTO Active_Orders (name, contract)
SELECT o.name, o.contract
FROM Old_Orders o
WHERE o.contract IN (SELECT contract FROM Move_Orders)
You could also do a INNER JOIN between old_orders and move_orders, which will cause moveorders to filter the list of oldorders down to just those also present in move_orders
INSERT INTO Active_Orders (name, contract)
SELECT o.name, o.contract
FROM
Old_Orders o
INNER JOIN Move_Orders m ON o.contract = m.contract

mysql select not does not work

I want to only select student IDs that do not have a row where product ID is 11. But I can't. What should I do?
BEGIN TRANSACTION;
CREATE TABLE STUDENTS(Id integer PRIMARY KEY, name text,year_born integer
);
CREATE TABLE PROJECT(project_id integer,title text,project_owner
text,year_written integer );
CREATE TABLE PROJECTWORKS(student_id integer,project_id integer);
INSERT INTO STUDENTS VALUES(1598,'james',1996);
INSERT INTO STUDENTS VALUES(2479,'andre',1996);
INSERT INTO STUDENTS VALUES(3682,'pierre',1997);
INSERT INTO PROJECT VALUES(10,'A','ABC',2008);
INSERT INTO PROJECT VALUES(11,'B','ABC',2010);
INSERT INTO PROJECT VALUES(12,'C','ABC',2016);
INSERT INTO PROJECT VALUES(13,'D','CBA',2014);
INSERT INTO PROJECTWORKS VALUES(1598,10);
INSERT INTO PROJECTWORKS VALUES(1598,11);
INSERT INTO PROJECTWORKS VALUES(1598,12);
INSERT INTO PROJECTWORKS VALUES(3682,12);
INSERT INTO PROJECTWORKS VALUES(3682,13);
INSERT INTO PROJECTWORKS VALUES(2479,12);
SELECT * FROM STUDENTS;
SELECT * FROM PROJECT;
SELECT * FROM PROJECTWORKS;
SELECT DISTINCT student_id FROM PROJECTWORKS
WHERE not project_id=11 and (project_id=10 OR project_id=12 OR
project_id=13);
I just want 3682 and 2479 Because 1598 has 11.
NOT EXISTS is perfect for this:
SELECT DISTINCT student_id
FROM PROJECTWORKS p
WHERE project_id IN (10, 12, 13)
AND NOT EXISTS
(SELECT 1
FROM PROJECTWORKS p2
WHERE p.student_id = p2.student_id
AND p2.project_id = 11);
Also, I assume you meant you don't want ID 11, as I didn't see 14 in your example.
If I understood you right, this is what you want
SELECT DISTINCT student_id FROM PROJECTWORKS
WHERE student_id not in
(select student_id from PROJECTWORKS where project_id=11)
You could use a join between the two result
select distinct student_id
from PROJECTWORKS p
where project_id NOT IN (11)
INNER JOIN (
Select distinct student_id
from PROJECTWORKS
where project_id IN ( 10, 12, 13)
) T on t.student_id = p.student_id
SELECT DISTINCT student_id FROM PROJECTWORKS
WHERE student_id not in
(select student_id from PROJECTWORKS where project_id=11)
Your question is not clear. above code snippet is for distinct student_id which does not have project_id as 11

Stored Procedure between two tables?

Let's say I have two tables, table-a and table-b.
Table-a has the following columns: product_id, mission_id, mission_status, mission_source, mission_destinition.
Table-b has two columns: product_id, location_id.
If I were to write a stored procedure which removes a row from table-a where mission_status=1, and then automatically create a new row in table-b consisting of the product_id and mission_destination from the row just removed in table-a, how would I write the stored procedure?
There are a few different ways to accomplish this. As someone said above, a trigger may be the way to go. Here's a simple script that might work in this case.
--Create test tables
CREATE TABLE #TEMP1
(
product_id int,
mission_Id int,
mission_status int,
mission_source int,
mission_destination VARCHAR(50)
);
CREATE TABLE #TEMP2
(
product_id int,
location_id VARCHAR(50)
);
--Test data
INSERT INTO #TEMP1
VALUES(1,1,1,2,'Mars')
INSERT INTO #TEMP1
VALUES(2,1,1,2,'Jupiter')
INSERT INTO #TEMP1
VALUES(3,1,1,2,'Venus')
INSERT INTO #TEMP1
VALUES(4,1,1,2,'Saturn')
--Check for mission_status of 1
SELECT product_id, mission_destination FROM #TEMP1 WHERE mission_status = 1
IF ##ROWCOUNT > 0
BEGIN
INSERT INTO #TEMP2 (product_id,location_id) SELECT product_id, mission_destination FROM #TEMP1 WHERE mission_status = 1
DELETE FROM #TEMP1 WHERE mission_status = 1
END
SELECT * FROM #TEMP1
SELECT * FROM #TEMP2

How to do Nested SUM in mysql

I have three tables invoice_lineItem, contract_Details and Tranche.
What I want to achieve is to get total purchase price of contracts based on contractID from invoice_lineItem and contract_Details and then get TotalPurchasePrice of all contract in the same tranche.
Here's the fiddle http://sqlfiddle.com/#!9/67123/1 of what I've tried
I get purchase price of contractID of other tranche added to
trancheID 1 as shown below
create table invoice_lineItem(
inv_id INT NOT NULL AUTO_INCREMENT ,
contractID VARCHAR(255),
purchasePrice INT,
PRIMARY KEY(inv_id)
);
create table contract_details(
contractID VARCHAR(255) NOT NULL,
funder VARCHAR(255),
PRIMARY KEY(contractID)
);
create table tranche_details(
contractID VARCHAR(255) NOT NULL,
trancheID VARCHAR(255),
PRIMARY KEY(contractID)
);
insert into invoice_lineItem(contractID,purchasePrice) VALUES ('1/14S/03',5);
insert into invoice_lineItem(contractID,purchasePrice) VALUES ('1/14S/03',5);
insert into invoice_lineItem(contractID,purchasePrice) VALUES ('2/14S/03',15);
insert into invoice_lineItem(contractID,purchasePrice) VALUES ('2/14S/03',15);
insert into invoice_lineItem(contractID,purchasePrice) VALUES ('3/14S/03',5);
insert into contract_details(contractID,funder) VALUES ('1/14S/03','ABC');
insert into contract_details(contractID,funder) VALUES ('2/14S/03','ABC');
insert into contract_details(contractID,funder) VALUES ('3/14S/03','ABC');
insert into tranche_details(contractID,trancheID) VALUES ('1/14S/03',1);
insert into tranche_details(contractID,trancheID) VALUES ('2/14S/03',1);
insert into tranche_details(contractID,trancheID) VALUES ('3/14S/03',2);
SELECT cd.contractID,SUM(inv.purchasePrice) as totalPP
FROM `contract_details` cd INNER JOIN invoice_lineitem inv ON inv.contractID=cd.contractID
WHERE cd.funder='ABC'
What i want to achieve is to get
totalPurchasePrice For All Contracts with same contractID and the
funder Name 'ABC' from ContractDetails
inv_id:1
contractID:1/14S/03
PurchasePrice:5
inv_id:2
contractID:1/14S/03
PurchasePrice:5
So total PurchasePrice is: 10 and similarly for 2/14S/03 it will be 30 and now since contractID:1/14S/03 and contractID:2/14S/03 are in same tranche I want to SUM their totalPurchase Price
SELECT cd.contractID,SUM(inv.purchasePrice) as totalPP FROM `contract_details` cd
INNER JOIN invoice_lineitem inv ON inv.contractID=cd.contractID
INNER JOIN tranche_details td ON td.trancheID=(SELECT trancheID FROM tranche_details GROUP by trancheID having COUNT(*)>1)
WHERE cd.funder='ABC' GROUP BY cd.contractID
Edit:
Here i found Solution DEMO http://sqlfiddle.com/#!9/69ee8/10
select td.trancheID,GROUP_CONCAT(td.contractID SEPARATOR ';') as allcontract,SUM(s.totalPP) as totalPPtranche
from tranche_details td
left join
(
SELECT cd.contractID,cd.funder,SUM(inv.purchasePrice) as totalPP FROM `contract_details` cd
INNER JOIN invoice_lineitem inv ON inv.contractID=cd.contractID
WHERE cd.funder='ABC' GROUP BY cd.contractID
) s
on td.contractID = s.contractID
WHERE s.funder='ABC'
GROUP BY (td.trancheID)

Issue in inserting the records using stored procedure with dynamic Id

I am writing a stored procedure to get a list of records from TableA and insert those records into TableB. now i'm facing issue in this.
Here is my sp :
USE [Sample_DB]
GO
SET ANSI_NULLS ON
GOenter code here
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddStoredProcedure]
AS
BEGIN
DECLARE #ProcessedData AS TABLE (Name varchar(200),MaritalStatus varchar(200))
INSERT INTO #ProcessedData (Name ,MaritalStatus )
SELECT Name,MaritalStatus from TableA where MaritalStatus='Male'
INSERT INTO [TableB]
(
Id
,Name
,MaritalStatus
)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((select MAX(Id)+1 from [TableA] where MaritalStatus='Male'),4),' ','0') as varchar)),Name,MaritalStatus FROM #ProcessedData
END
TableA contains,
Id Name MaritalStatus
1 John Male
2 Sam Male
3 Seema Female
when i execute the stored procedure, AddStoredProcedure
I'm getting the output as
TableB contains,
Id Name MaritalStatus
M_13_0003 John Male
M_13_0003 Sam Male
But i need as below;
TableB should be,
Id Name MaritalStatus
M_13_0003 John Male
M_13_0004 Sam Male
Thank you all in advance for your response.
You can use row_number function as:
DECLARE #ProcessedData AS TABLE (Name varchar(200),MaritalStatus varchar(200))
INSERT INTO #ProcessedData (Name ,MaritalStatus )
SELECT Name,MaritalStatus from TableA where MaritalStatus='Male'
DECLARE #IdMax int;
SELECT #IdMax = MAX(Id)
FROM [TableA]
WHERE MaritalStatus='Male';
INSERT INTO [TableB]
(
Id
,Name
,MaritalStatus
)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((row_number() over(Order by Name)+#IdMax ),4),' ','0') as varchar)),
Name,MaritalStatus
FROM #ProcessedData
DECLARE #TableA TABLE (Id INT, Name VARCHAR(20), MaritalStatus VARCHAR(6))
DECLARE #TableB TABLE (Id VARCHAR(9), Name VARCHAR(20), MaritalStatus VARCHAR(6))
INSERT INTO #TableA (Id, Name, MaritalStatus)
VALUES
(1, 'John', 'Male'),
(2, 'Sam', 'Male'),
(3, 'Seema', 'Female')
DECLARE #ProcessedData AS TABLE (Id INT IDENTITY(1,1), Name varchar(200),MaritalStatus varchar(200))
INSERT INTO #ProcessedData (Name ,MaritalStatus )
SELECT Name
,MaritalStatus
FROM #TableA
WHERE MaritalStatus='Male'
INSERT INTO #TableB (Id, Name, MaritalStatus)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((select MAX(Id) from #TableA where MaritalStatus='Male')+Id,4),' ','0') as varchar))
,Name
,MaritalStatus
FROM #ProcessedData
SELECT * FROM #TableB
I've replaced your tables with table variables so it runs straight off the bat.
Is there any reason you want to start from 0003? This query will produce your desired output anyway, comment if you need changes.