MS SQL Server 2012 - Insert Values if row does not exist - sql

I'm new to SQL and I need to check whether or not values in a row exist before I insert them.
I am attempting to insert details to several rows at once.
The code I have is as follows:
insert into [Test].[Projects]([TestID], [GroupID], [TestingID], [Grade])
values
(314, 9, 77, 2)
,(314, 9, 77, 3)
,(314, 9, 77, 4)
,(329, 2, 65, 2)
,(329, 2, 65, 3)
,(329, 2, 65, 4)
go
If someone could help me to insert these where the row values do not exist then I would be very grateful

You could use the insert ... select syntax with a not exists condition that ensures that the very same record is not already there in the table:
insert into Test.Projects(TestID, GroupID, TestingID, Grade)
select v.*
from (values
(314, 9, 77, 2),
(314, 9, 77, 3),
(314, 9, 77, 4),
(329, 2, 65, 2),
(329, 2, 65, 3),
(329, 2, 65, 4)
) v(TestID, GroupID, TestingID, Grade)
where not exists (
select 1
from Test.Projects p
where
p.TestID = v.TestID
and p.GroupID = v.GroupID
and p.TestingID = v.TestingID
and p.Grade = v.Grade
)

Related

SQL. Where condition for multiple values of column

Im looking for some hint when trying to filter for multiple values within column.
I'm interested in an "AND" condition for some values in column X (ie. statement Where Column X in (1,2,3) doesn't fulfill my needs).
Consider this example table:
I'm interested in finding COD_OPE that has both status 6 and 7. In this example i'm interested to find only COD_OPE = 3
If i use Where status in (6,7) i'll get cod_ope 1 and 6.
Any smart way to find cod_ope = 3?
Thank you!
Code for table in the example:
CREATE TABLE [TABLE] (
COD_OPE int,
STATUS int,
Observation_date int
)
INSERT INTO [TABLE] (COD_OPE, STATUS, Observation_date)
VALUES (1, 1, 2022),(1, 1, 2021), (1, 1, 2020), (1, 6, 2019), (1, 6, 2018), (2, 1, 2022), (2, 7, 2021), (2, 4, 2020), (2, 4, 2019), (2, 7, 2018), (3, 1, 2022), (3, 1, 2021), (3, 4, 2020), (3, 7, 2019), (3, 6, 2018)
select * from [TABLE]
Use aggregation:
SELECT COD_OPE
FROM [TABLE]
WHERE STATUS IN (6, 7)
GROUP BY COD_OPE
HAVING COUNT(DISTINCT STATUS) = 2;

summing by rows sql

I attempted to do it using the analytical function, but it appears that I did so improperly...
How can I receive the output from the table I've been given?
CREATE TABLE rides (
ride_id INT,
driver_id INT,
ride_in_kms INT,
ride_fare FLOAT,
ride_date DATE
);
INSERT INTO rides VALUES (1, 1, 3, 4.45, "2016-05-16");
INSERT INTO rides VALUES (2, 1, 4, 8.46, "2016-05-16");
INSERT INTO rides VALUES (3, 2, 6, 11.9, "2016-05-16");
INSERT INTO rides VALUES (4, 3, 3, 6.76, "2016-05-16");
INSERT INTO rides VALUES (5, 2, 6, 13.55, "2016-05-16");
INSERT INTO rides VALUES (6, 4, 3, 4.91, "2016-05-20");
INSERT INTO rides VALUES (7, 1, 7, 16.77, "2016-05-20");
INSERT INTO rides VALUES (8, 3, 9, 16.18, "2016-05-20");
INSERT INTO rides VALUES (9, 2, 3, 6.07, "2016-05-20");
INSERT INTO rides VALUES (10, 4, 4, 6.25, "2016-05-20");
Output result
Thanks in advance
The general gist is to use an expression within the sum() to operate on the correct rows:
select
driver_id,
sum(case when ride_date = "2016-05-16" then ride_in_kms else 0 end) `KMS_MAY_16`,
sum(case when ride_date = "2016-05-20" then ride_in_kms else 0 end) `KMS_MAY_20`
from
group by driver_id;
The particular syntax available, and how to express the column label depends on what database you are using.

Multiple Inserts in SQL Developer [duplicate]

This question already has answers here:
Best way to do multi-row insert in Oracle?
(9 answers)
Closed last year.
I tried to do below insert in SQL Developer
insert into tabletest values
(1, null, 23, 2020),
(2, null, 23, 2021),
(3, 77, 23, 2022),
(4, 77, 23, 2023),
(5, 77, 23, 2024),
(6, null, 23, 2025);
But it's giving me below error
Error report -
SQL Error: ORA-00933: SQL command not properly ended
00933. 00000 - "SQL command not properly ended"
Can someone tell me what's the error in the query please
For multiple inserts in the Oracle database, you can use one of these solutions
insert all
into tabletest values (1, null, 23, 2020)
into tabletest values (2, null, 23, 2021)
into tabletest values (3, 77, 23, 2022)
into tabletest values (4, 77, 23, 2023)
into tabletest values (5, 77, 23, 2024)
into tabletest values (6, null, 23, 2025)
select * from dual
;
or
insert into tabletest
select 1, null, 23, 2020 from dual union all
select 2, null, 23, 2021 from dual union all
select 3, 77, 23, 2022 from dual union all
select 4, 77, 23, 2023 from dual union all
select 5, 77, 23, 2024 from dual union all
select 6, null, 23, 2025 from dual
;

Sum over range but reset when other column value is 1

So I have an account number and a reading number that I want to take the cumulative sum of but reset at the beginning of a new reading cycle (I want to reset the running sum).
I am using a window function but cannot figure out how to set it when the new reading cycle exists.
Data has the following format:
The Reading cycle Volume value is what I am attempting to achieve.
Currently I have tried SUM(Value) OVER(PARTITION BY ACCOUNT ORDER BY OBS)
I do not know how to reset it when reading # = 1.
I have tried:
Case
when [Reading #] = 1 THEN value
ELSE SUM(Value) OVER(PARTITION BY ACCOUNT ORDER BY OBS)
END AS [Running Total]
If I understand the question correctly and the values, stored in the Obs and [Reading #] columns are without gaps, the next approach is an option:
Table:
SELECT *
INTO Data
FROM (VALUES
(1, 1, 1, 5),
(1, 2, 2, 6),
(1, 3, 3, 5),
(1, 4, 4, 6),
(1, 5, 5, 5),
(1, 6, 6, 5),
(1, 7, 1, 5),
(1, 8, 2, 6),
(1, 9, 3, 5),
(1, 10, 4, 6),
(1, 11, 5, 5),
(1, 12, 6, 5),
(2, 1, 1, 7),
(2, 2, 2, 8),
(2, 3, 3, 9),
(2, 4, 4, 10),
(2, 5, 5, 11),
(2, 6, 6, 12),
(2, 7, 1, 7),
(2, 8, 2, 8),
(2, 9, 3, 9),
(2, 10, 4, 10),
(2, 11, 5, 11),
(2, 12, 6, 12)
) v (Account, Obs, [Reading #], [Value])
Statement:
SELECT
Account, Obs, [Reading #], [Value],
SUM([Value]) OVER (PARTITION BY Account, [Group] ORDER BY Account, Obs) AS [Ready Cicle Value]
FROM (
SELECT
*,
(Obs - [Reading #]) AS [Group]
FROM Data
) t
One additional option (as a more general approach) is to create groups when [Reading #] is equal to 1:
SELECT
Account, Obs, [Reading #], [Value],
SUM([Value]) OVER (PARTITION BY Account, [Group] ORDER BY Obs) AS [Ready Cicle Value]
FROM (
SELECT *, SUM([Change]) OVER (PARTITION BY Account ORDER BY Obs) AS [Group]
FROM (
SELECT *, CASE WHEN [Reading #] = 1 THEN 1 ELSE 0 END AS [Change]
FROM Data
) a
) b
Help us to help you. Always include a minimal set of data and the code we need, which we can copy and paste to immediately be on the same page as you without wasting time & effort that is better spent helping others. Note how you can simply copy and paste our solutions and play with them? They are complete and stand alone. That is what we are looking for from you.
You are close. The piece you are missing is that you need some way to group your readings and then you can include that in your partitioning as well.
There are any number of ways to create the new derived value for "reading_group" the following is just one way.
DECLARE #t_customer_readings TABLE
( account_number INT,
observation INT,
reading_number INT,
reading_value INT
)
INSERT INTO #t_customer_readings
VALUES (1, 1 , 1, 3),
(1, 2 , 2, 6),
(1, 3 , 3, 9),
(1, 4 , 4, 5),
(1, 5 , 5, 5),
(1, 6 , 6, 8),
(1, 7 , 1, 1),
(1, 8 , 2, 4),
(1, 9 , 3, 7),
(1, 10, 4, 0),
(1, 11, 5, 3),
(1, 12, 6, 6),
(2, 1 , 1, 9),
(2, 2 , 2, 2),
(2, 3 , 3, 5),
(2, 4 , 4, 8),
(2, 5 , 5, 1),
(2, 6 , 6, 4),
(2, 7 , 1, 7),
(2, 8 , 2, 0),
(2, 9 , 3, 3),
(2, 10, 1, 6), -- note I have split this group into 2 to show that the reading numbers do not need to be sequential.
(2, 11, 5, 9),
(2, 12, 6, 2)
SELECT r.*,
-- reading_group = CASE WHEN r.reading_number = 1 THEN observation ELSE rg.reading_group END,
ready_cycle_volume = SUM(reading_value) OVER(PARTITION BY account_number,
CASE WHEN r.reading_number = 1 THEN observation
ELSE rg.reading_group
END
ORDER BY observation)
FROM #t_customer_readings r
CROSS APPLY
(SELECT reading_group = MAX(observation) -- I picked observation but you could use whatever value you like. we are just creating something we can group on.
FROM #t_customer_readings
WHERE account_number = r.account_number
AND observation < r.observation
AND reading_number = 1) rg

SQL request error

Good evening everyone,
I'm working on a assignment and can't figure out the following, I have two tables:
CREATE TABLE Rental (
rental_id DECIMAL(12) PRIMARY KEY,
customer_id DECIMAL(12),
movie_id DECIMAL(12),
delivery_status VARCHAR(64),
return_status VARCHAR(64));
and
CREATE TABLE Movie (
movie_id DECIMAL(12) PRIMARY KEY,
DVD_id INTEGER NOT NULL,
title VARCHAR(64) NOT NULL,
stock_number DECIMAL(12),
director_id DECIMAL(12),
genre_id DECIMAL(12),
release_date DATE NOT NULL,
restrictions VARCHAR(256) NOT NULL);
I need to do the following, list the names of all movies that are currently unavailable, rented and not yet returned. And this is my query:
SELECT Movie.movie_id, Movie.title, Movie.stock_number
FROM Movie
WHERE (Movie.movie_id, Movie.stock_number) NOT IN (
SELECT Rental.movie_id,
COUNT(Rental.return_status) AS number_of_unreturned
FROM Rental
WHERE Rental.return_status = 'Unreturned'
GROUP BY Rental.movie_id
HAVING COUNT (Rental.return_status) > 1) AND Movie.stock_number = 0;
I definitely have movies in Movie table that are not "Unreturend" but I get no rows selected all the time. Any advices or directions to think would be appreciated. Thanks!
I edited this post and added the content of the tables.
INSERT INTO Movie VALUES (1, 1, 'Amblin', 1, 1, 1, CAST('18-Dec-1968' AS DATE), 'G');
INSERT INTO Movie VALUES (2, 2, 'Duel', 2, 1, 2, CAST('13-Nov-1971' AS DATE), 'R');
INSERT INTO Movie VALUES (3, 3, 'Something Evil ', 3, 1, 3, CAST('21-Jan-1972' AS DATE), 'R');
INSERT INTO Movie VALUES (4, 4, 'The Sugarland Express ', 4, 1, 4, CAST('05-Apr-1974' AS DATE), 'PG13');
INSERT INTO Movie VALUES (5, 5, 'Jaws', 5, 1, 3, CAST('20-Jun-1975' AS DATE), 'R');
INSERT INTO Movie VALUES (6, 6, 'Close Encounters of the Third Kind', 6, 1, 5, CAST('16-Nov-1977' AS DATE), 'PG13');
INSERT INTO Movie VALUES (7, 7, ' 1941', 7, 1, 6, CAST('14-Dec-1979' AS DATE), 'G');
INSERT INTO Movie VALUES (8, 8, 'Raiders of the Lost Ark', 8, 1, 7, CAST('12-Jun-1981' AS DATE), 'PG13');
INSERT INTO Movie VALUES (9, 9, 'E.T. the Extra-Terrestrial', 9, 1, 5, CAST('11-Jun-1982' AS DATE), 'PG13');
INSERT INTO Movie VALUES (10, 10, 'Twilight Zone: The Movie', 10, 1, 3, CAST('24-Jun-1983' AS DATE), 'R');
INSERT INTO Movie VALUES (11, 11, 'Indiana Jones and the Temple of Doom', 11, 1, 7, CAST('23-May-1984' AS DATE), 'PG13');
INSERT INTO Movie VALUES (12, 12, 'The Color Purple', 12, 1, 4, CAST('18-Dec-1985' AS DATE), 'G');
INSERT INTO Movie VALUES (13, 13, 'Empire of the Sun', 13, 1, 4, CAST('25-Dec-1987' AS DATE), 'G');
INSERT INTO Movie VALUES (14, 14, 'Always', 14, 1, 4, CAST('22-Dec-1989' AS DATE), 'G');
INSERT INTO Movie VALUES (15, 15, 'Indiana Jones and the Last Crusade', 15, 1, 7, CAST('24-May-1989' AS DATE), 'G');
INSERT INTO Movie VALUES (16, 16, 'Hook', 16, 1, 8, CAST('11-Dec-1991' AS DATE), 'G');
INSERT INTO Movie VALUES (17, 17, 'Jurassic Park ', 17, 1, 5, CAST('11-Jun-1993' AS DATE), 'PG13');
INSERT INTO Movie VALUES (18, 18, 'Schindler''s List', 18, 1, 4, CAST('15-Dec-1993' AS DATE), 'PG13');
INSERT INTO Movie VALUES (19, 19, 'The Lost World: Jurassic Park', 19, 1, 5, CAST('23-May-1997' AS DATE), 'PG13');
INSERT INTO Movie VALUES (20, 20, 'Amistad', 20, 1, 4, CAST('10-Dec-1997' AS DATE), 'PG13');
INSERT INTO Movie VALUES (21, 21, 'Saving Private Ryan', 21, 1, 4, CAST('24-Jul-1998' AS DATE), 'PG13');
INSERT INTO Movie VALUES (22, 22, 'A.I. Artificial Intelligence', 22, 1, 4, CAST('29-Jun-2001' AS DATE), 'PG13');
INSERT INTO Movie VALUES (23, 23, 'Minority Report', 23, 1, 7, CAST('21-Jun-2002' AS DATE), 'PG13');
INSERT INTO Movie VALUES (24, 24, 'Catch Me If You Can', 24, 1, 8, CAST('25-Dec-2002' AS DATE), 'PG13');
INSERT INTO Movie VALUES (25, 25, ' The Terminal', 25, 1, 4, CAST('18-Jun-2004' AS DATE), 'G');
INSERT INTO Movie VALUES (26, 26, 'War of the Worlds', 26, 1, 5, CAST('29-Jun-2005' AS DATE), 'PG13');
INSERT INTO Movie VALUES (27, 27, 'Munich', 27, 1, 4, CAST('23-Dec-2005' AS DATE), 'PG13');
INSERT INTO Movie VALUES (28, 28, 'Indiana Jones and the Kingdom of the Crystal Skull', 28, 1, 7, CAST('22-May-2008' AS DATE), 'PG13');
INSERT INTO Movie VALUES (29, 29, 'The Adventures of Tintin', 28, 1, 7, CAST('21-Dec-2011' AS DATE), 'PG13');
INSERT INTO Movie VALUES (30, 30, 'War Horse', 30, 1, 4, CAST('25-Dec-2011' AS DATE), 'PG13');
INSERT INTO Movie VALUES (31, 31, 'Lincoln', 31, 1, 4, CAST('09-Nov-2012' AS DATE), 'PG13');
INSERT INTO Movie VALUES (32, 32, 'Bridge of Spies', 32, 1, 4, CAST('16-Oct-2015' AS DATE), 'PG13');
INSERT INTO Movie VALUES (33, 33, 'The BFG', 33, 1, 8, CAST('01-Jul-2016' AS DATE), 'PG13');
INSERT INTO Movie VALUES (34, 34, 'Praying with Anger', 34, 2, 5, CAST('12-Sep-1992' AS DATE), 'PG13');
INSERT INTO Movie VALUES (35, 35, 'Wide Awake', 35, 2, 4, CAST('20-Mar-1998' AS DATE), 'G');
INSERT INTO Movie VALUES (36, 36, 'The Sixth Sense', 36, 2, 2, CAST('06-Aug-1999' AS DATE), 'PG13');
INSERT INTO Movie VALUES (37, 37, 'Unbreakable', 37, 2, 2, CAST('22-Nov-2000' AS DATE), 'PG13');
INSERT INTO Movie VALUES (38, 38, 'Signs', 38, 2, 2, CAST('02-Aug-2002' AS DATE), 'PG13');
INSERT INTO Movie VALUES (39, 39, 'The Village', 39, 2, 2, CAST('30-Jul-2004' AS DATE), 'PG13');
INSERT INTO Movie VALUES (40, 40, 'Lady in the Water', 40, 2, 8, CAST('21-Jul-2006' AS DATE), 'PG13');
INSERT INTO Movie VALUES (41, 41, 'The Happening', 41, 2, 2, CAST('13-Jun-2008' AS DATE), 'R');
INSERT INTO Movie VALUES (42, 42, 'The Last Airbender', 42, 2, 7, CAST('02-Jul-2010' AS DATE), 'G');
INSERT INTO Movie VALUES (43, 43, 'After Earth', 43, 2, 7, CAST('31-May-2013' AS DATE), 'G');
INSERT INTO Movie VALUES (44, 44, 'The Visit', 44, 2, 3, CAST('11-Sep-2015' AS DATE), 'R');
INSERT INTO Movie VALUES (45, 45, 'Split', 45, 2, 2, CAST('20-Jan-2017' AS DATE), 'PG13');
and
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 1, 1, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 2, 1, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 3, 6, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 4, 7, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 2, 2, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 2, 37, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 5, 1, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 5, 24, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 5, 3, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 6, 13, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 6, 2, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 6, 8, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 6, 1, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 5, 2, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 5, 3, 'Delivered', 'Unreturned');
INSERT INTO Rental VALUES (sequence_rental.NEXTVAL, 3, 27, 'Delivered', 'Returned');
Sorry if that is a too long post.
I don't want to write the code since you are a student. I'll give some direction though. In your where clause you're comparing (movie.movie_id = rental.movie_id) and (movie.stock_number = count(rental.return_status). Comparing the stock_number to the count of returns is incorrect.
When returning columns from multiple tables, use a join. The in statement does a comparison. Count is not being returned.
Join movies and the "in" subquery on movie_id. Create an alias on the subquery so you can join it.
Add the count column to the topmost outer select
Please try, if this logic is correct, I did not quite understand column naming. You might change last row (having) to correct it.
SELECT
m.movie_id, m.title, m.stock_number -- Getting movie id, movie title, stock number
FROM Movie m -- from movie table
JOIN rental r
ON (m.movie_id = r.movie_id) -- joining rental table in movie_id
WHERE
r.return_status = 'Unreturned' -- where return_status is unreturned
GROUP BY
m.movie_id, m.title, m.stock_number -- grouping_by (same as select)
HAVING
SUM(r.movie_id) > m.stock_number; -- restricting group by quantity
To resolve the query try first to break it down in the components you need.
In this case you need to compare the number of rented movies against the stock of movies.
So write 2 separte queries:
1 - One that will provide the movie id and the number to movies in stock.
2 - Another for the movie id and the number of rentals. For this one you have to count the unretured.
After you have the two queries, you can use them as subqueries of a higer level query that treats each or these queries as a table joined by the common id field.
And add awhere clause comparing the stock with the counted field.
Example:
Table A: id, name, age
Table B: table_b_id, table_a_id, telephone, address
Query 1: select id, name, age from A
Query 2: select table_a_id, telephone, address from B
select Q1.id, Q1.name, Q1.age, Q2telephone, Q2.address
from
(select A.id, A.name, A.age from A) Q1,
(select B.table_a_id, B.telephone, B.address from B) Q2
where
Q1.id = Q2.table_a_id