How to add temp table to another temp table with extra column - sql

CREATE TABLE #EmpPcodes
(
YearMonth INT,
YEAR INT,
MONTH INT,
RunNo INT,
Amount NUMERIC(18, 3),
GroupCode NvarCHAR(30),
GroupName NvarCHAR(250),
GroupAName NvarCHAR(250),
PayrollGroup INT,
EmployeeId INT
)
CREATE TABLE #pArrangeAllcode
(
YearMonth INT,
YEAR INT,
MONTH INT,
RunNo INT,
Amount NUMERIC(18, 3),
GroupCode NvarCHAR(30),
GroupName NvarCHAR(250),
GroupAName NvarCHAR(250),
PayrollGroup INT,
EmployeeId INT,
CodeArrange INT
)
INSERT INTO #pArrangeAllcode
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName,
GroupAName, PayrollGroup, EmployeeId,
FROM dbo.#EmpPcodes
SELECT * FROM #pArrangeAllcode
I expect to get the data from the #EmPcodes temp table to #pArrangeAllcode
but it has extra column that I'll use it later ... I always get this error :
Insert Error: Column name or number of supplied values does not match table definition.
Any Help ?

Actually you are missing one column in insert statement whch also need some value:
use this:
INSERT INTO #pArrangeAllcode
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName,
GroupAName, PayrollGroup, EmployeeId,NULL
FROM dbo.#EmpPcodes

Use below query for inserting records.
INSERT INTO #pArrangeAllcode
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName,
GroupAName, PayrollGroup, EmployeeId,NULL
FROM dbo.#EmpPcodes

CodeArrange is the extra column exist in the #pArrangeAllcode table. Since it is NOT NULL column, you can skip the particular column name in the insert block and explicitly mention the column name is the INSERT statement.
INSERT INTO #pArrangeAllcode (YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId)
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId
FROM #EmpPcodes
or if you want to store some dummy value in the CodeArrange column then pass NULL
INSERT INTO #pArrangeAllcode (YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId, CodeArrange)
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId, NULL
FROM #EmpPcodes

INSERT INTO #pArrangeAllcode
SELECT dbo.#EmpPcodes.*, NULL
FROM dbo.#EmpPcodes

Related

Column name or number of supplied values does not match table definition.?

Drop table if exists #populationpercentagevaccine
Create Table #populationpercentagevaccine
(
Continent nvarchar(255),
location nvarchar(255),
Date Datetime,
Population numeric,
New_vaccinations numeric,
cumulative_vaccine numeric
)
My table is executing perfect but that code INSERT INTO giving me problem
Insert into #populationpercentagevaccine
select death.Continent, death.location, death.Date, death.Population, vaccine.New_vaccinations,
sum(convert(int,vaccine.new_vaccinations )) over(partition by death.location order by death.location, death.date) as cumulative_all_vaccine
I created table and inserting into that same table what is causing Column name or number of supplied values does not match table definition that problem
Your table columns and supplied columns in insert was not matching earlier.
Insert into #populationpercentagevaccine
select Continent, [location], [Date], [Population], New_vaccinations
, sum(convert(int,new_vaccinations )) over(partition by [location] order by [location, [date]) as cumulative_all_vaccine
from #populationpercentagevaccine
This was your previous question:
Create Table #populationpercentagevaccine
(
Continent nvarchar(255),
location nvarchar(255),
Date Datetime,
Population numeric,
New_vaccinations numeric,
cumulative_vaccine numeric,
cumulative_all_vaccine numeric
)
Insert into #populationpercentagevaccine
select Continent, [location], [Date], [Population], New_vaccinations, cumulative_vaccine --this was missing earlier
, sum(convert(int,new_vaccinations )) over(partition by [location]
order by [location, [date]) as cumulative_all_vaccine
from #populationpercentagevaccine
your table has 7 columns, your query supplies values only for 6 of them.
either supply the value or insert the identity

Rownumber to select non duplicate or distinct rows from a table. Invalid name ''

I am trying to select non-duplicate rows from emp_demo2 table:
Table:
CREATE TABLE Emp_demo3 (
emp_ID INT,
emp_Name NVARCHAR (50),
emp_sal_K INT,
emp_manager INT,
joining_date date,
last_time date)
GO
INSERT INTO Emp_demo3 VALUES (1,'Ali', 200,2,'2010-01-28','2015-05-09')
INSERT INTO Emp_demo3 VALUES (2,'Zaid', 770,4,'2008-01-28','2015-05-09')
INSERT INTO Emp_demo3 VALUES (3,'Mohd', 1140,2,'2007-01-28','2015-05-09')
INSERT INTO Emp_demo3 VALUES (4,'LILY', 770,Null,'2013-01-28','2015-05-09')
INSERT INTO Emp_demo3 VALUES (5,'John', 1240,6,'2016-01-28','2015-05-09')
INSERT INTO Emp_demo3 VALUES (6,'Mike', 1140,4,'2018-01-28','2015-05-09')
INSERT INTO Emp_demo3 VALUES (5,'John', 1240,6,'2017-01-28','2015-05-09')
INSERT INTO Emp_demo3 VALUES (3,'Mohd', 1140,2,'2010-01-28','2015-05-09')
Code to add column date_difference
alter table emp_demo3
add date_diff date
go
update emp_demo3 set date_diff = datediff(day,joining_date, last_time)
I am trying to calculate date difference in days between 2 dates. Please note that this is just a random table I created. I cannot change date formats in my original table. So please tell how to get date difference with existing date formats.
Error
Operand type clash: int is incompatible with date
You can use ROW_Number to make partitions by columns which are the same. Then it is necessary just filter rows which have rownum = 1:
An example:
DECLARE #Emp_demo2 TABLE (
emp_ID INT,
emp_Name NVARCHAR (50),
emp_sal_K INT,
emp_manager INT)
INSERT INTO #Emp_demo2 VALUES (1,'Ali', 200,2)
INSERT INTO #Emp_demo2 VALUES (2,'Zaid', 770,4)
INSERT INTO #Emp_demo2 VALUES (3,'Mohd', 1140,2)
INSERT INTO #Emp_demo2 VALUES (4,'LILY', 770,Null)
INSERT INTO #Emp_demo2 VALUES (5,'John', 1240,6)
INSERT INTO #Emp_demo2 VALUES (6,'Mike', 1140,4)
INSERT INTO #Emp_demo2 VALUES (5,'John', 1240,6)
INSERT INTO #Emp_demo2 VALUES (3,'Mohd', 1140,2)
SELECT * FROM
(
SELECT
t.emp_ID
, t.emp_Name
, t.emp_sal_K
, t.emp_manager
, ROW_NUMBER() OVER (PARTITION BY t.emp_Name, t.emp_sal_K, t.emp_manager
ORDER BY t.emp_Name) AS RowNum
FROM #Emp_demo2 AS t
)q
WHERE q.RowNum = 1
ORDER BY q.emp_ID
Following query is to find duplicates
select
distinct emp_ID,
emp_Name,
emp_sal_K,
emp_manager
from
(
select *,
count(*) over (partition by emp_id) as total
from Emp_demo2 e
) val
where total > 1
order by
emp_ID
If you want only distinct values then you can use following
select
distinct emp_ID,
emp_Name,
emp_sal_K,
emp_manager
from Emp_demo2 e
order by
emp_ID
METHOD 1:
SELECT DISTINCT * from #EmP_demo2
METHOD 2:
;WITH CTE AS(
SELECT * , ROW_NUMBER() OVER(PARTITION BY EMP_ID ORDER BY EMP_ID) AS ROWNUM
FROM #EMP_DEMO2 E
)
SELECT * FROM CTE WHERE ROWNUM=1
METHOD 3:
By using Group by also we ca avoid this duplicates.
Hope this works fine for your case
you can use this query,
select * from (select ROW_NUMBER() over(partition by emp_id order by emp_id) AS Rownum, * from Emp_demo2 as e
)x
where x.Rownum = 1

Get SQL Distinct Row Without NULL Values

I'm trying to get a distinct row using SQL from set of records that have matching key/id value, but NULLs in different columns. Hard to explain so please see screenshot. Any ideas?
create temporary table my_table (
id varchar(30), segmentdate1 date, converted1 varchar(10), segmentdate2 date, converted2 varchar(10)
);
insert into my_table (
id, segmentdate1, converted1, segmentdate2, converted2
)
values
('Michael','9/15/2020','No',NULL,NULL),
('Michael',NULL,NULL,'7/1/2019','Yes')
;
You seem to want aggregation:
select id, max(segmentdate1) as segmentdate1, max(converted1) as converted1,
max(segmentdate2) as segmentdate2, max(converted2) as converted2
from t
group by id;
Note: I made up names for the columns so they are unique.
This is probably a result set created from another query. That query probably has the wrong group by keys. You should probably fix that query.
declare #my_table table (
id varchar(30), segmentdate1 date, converted1 varchar(10), segmentdate2 date, converted2 varchar(10)
);
insert into #my_table (
id, segmentdate1, converted1, segmentdate2, converted2
)
values
('Michael','9/15/2020','No',NULL,NULL),
('Michael',NULL,NULL,'7/1/2019','Yes')
;
select id,max(isnull(segmentdate1,'1200-01-01')) segmentdate2
,max(isnull(converted1,'')) converted1, max(isnull(segmentdate2,'1200-01-01')) segmentdate2
,max(isnull(converted2,'')) converted2
from #my_table
group by id

How to get the Values of recently inserted columns from Temporary Table?

I am not able to use the recently inserted Quantity value of #ACCT table in the Select statement to be used like
ser.ServiceRate * Quantity
Every time I get the ERROR
Cannot insert the value NULL into column 'Amount'
I am just a beginner so any pointers to solve this would help.
DECLARE #MinReservationId INT = (SELECT MIN(f.ReservationId) FROM dbo.Reservation AS f)
DECLARE #MaxReservationId INT = (SELECT MAX(f.ReservationId) FROM dbo.Reservation AS f)
DECLARE #QuantityNew INT
WHILE #MinReservationId <= #MaxReservationId
BEGIN
CREATE TABLE #Acct
(
ServiceId INT,
Quantity INT --> I WANT THIS VALUE TO BE USED BELOW
)
INSERT INTO dbo.[Transaction]
(
ReservationId,
ServiceId,
Rate,
Quantity,
Amount
)
OUTPUT inserted.ServiceId,Inserted.Quantity
INTO #Acct
(
ServiceId,
Quantity
)
SELECT
#MinReservationId,
ser.ServiceId,
ser.ServiceRate,
ABS(CHECKSUM(NEWID())%3) + 1,
ser.ServiceRate * (SELECT acc.Quantity from #Acct as acc) -> QUANTITY from #ACCT should be used here
FROM dbo.[Service] AS ser
SELECT #MinReservationId=#MinReservationId+1
Drop table #Acct
END
You can use a CTE in order to capture the NEWID() value created for every record of table dbo.[Service]. Then use this CTE to do the INSERT:
;WITH ToInsert AS
(
SELECT ServiceId ,
ServiceRate,
ABS(CHECKSUM(NEWID())%3) + 1 AS Quantity
FROM dbo.[Service]
)
INSERT INTO dbo.[Transaction]
(
ReservationId,
ServiceId,
Rate,
Quantity,
Amount
)
SELECT #MinReservationId,
ServiceId,
ServiceRate,
Quantity,
ServiceRate * Quantity
FROM ToInsert

order a record by date field's month

Hello I have a table in mssql 2008 that contains a date field.
I'd like to make a select statement which will list all members, sorted by month only.
how do I access only the month part of the date field?
here are some of the member table fields:
id varchar(9) primary key,
f_name varchar(20),
l_name varchar(20),
f_name_english varchar(20),
l_name_english varchar(20),
gender varchar(20),
experience int,
b_date date,
passport varchar(20),
You can also use month() function. (or datepart(month, b_date))
Select id, f_name, l_name....
From YourTableName
Order by month(b_date)
Try this one -
SELECT id
, f_name
, l_name
, f_name_english
, l_name_english
, gender
, experience
, b_date
, passport
FROM YOUR_TABLE
ORDER BY MONTH(b_date)
SELECT * FROM YOURTABLE T
ORDER BY DATEPART(MONTH,T.b_date)
Include DATEPART(YEAR,T.b_date) to ORDER BY if you want to order a result by year too
this will sort by year & month
SELECT
id, f_name, l_name....
FROM
YOUR_TABLE
ORDER BY
CONVERT(Nvarchar(7), b_date, 121)
--or use DatePart(Month, b_date)
-- if you don't care about the year.