How to exclude in SQL with WHERE clause? - snowflake-cloud-data-platform

I have a WHERE clause in a large query that always exclude all records with the colour RED.
I however want to add another WHERE clause that exclude all records with the colour RED EXCEPT for when the age of the car is = 5.
Here's a some dummy data to better visualize how my data is built:
How would I integrate this into my large query to achieve this?
Here is my current query:
SELECT * FROM
TABLE1
WHERE COLOUR NOT LIKE '%RED%';
How would I modify this query to exclude all RED records EXCEPT when AGE = 5?
I am working in Snowflake.

The second condition needs to be connected using OR:
SELECT *
FROM TABLE1
WHERE COLOUR NOT LIKE '%RED%'
OR AGE = 5;

Related

Need to Add Values to Certain Items

I have a table that I need to add the same values to a whole bunch of items
(in a nut shell if the item doesn't have a UNIT of "CTN" I want to add the same values i have listed to them all)
I thought the following would work but it doesn't :(
Any idea what i am doing wrong ?
INSERT INTO ICUNIT
(UNIT,AUDTDATE,AUDTTIME,AUDTUSER,AUDTORG,CONVERSION)
VALUES ('CTN','20220509','22513927','ADMIN','AU','1')
WHERE ITEMNO In '0','etc','etc','etc'
If I understand correctly you might want to use INSERT INTO ... SELECT from original table with your condition.
INSERT INTO ICUNIT (UNIT,AUDTDATE,AUDTTIME,AUDTUSER,AUDTORG,CONVERSION)
SELECT 'CTN','20220509','22513927','ADMIN','AU','1'
FROM ICUNIT
WHERE ITEMNO In ('0','etc','etc','etc')
The query you needs starts by selecting the filtered items. So it seems something like below is your starting point
select <?> from dbo.ICUNIT as icu where icu.UNIT <> 'CTN' order by ...;
Notice the use of schema name, terminators, and table aliases - all best practices. I will guess that a given "item" can have multiple rows in this table so long as ICUNIT is unique within ITEMNO. Correct? If so, the above query won't work. So let's try slightly more complicated filtering.
select distinct icu.ITEMNO
from dbo.ICUNIT as icu
where not exists (select * from dbo.ICUNIT as ctns
where ctns.ITEMNO = icu.ITEMNO -- correlating the subquery
and ctns.UNIT = 'CTN')
order by ...;
There are other ways to do that above but that is one common way. That query will produce a resultset of all ITEMNO values in your table that do not already have a row where UNIT is "CTN". If you need to filter that for specific ITEMNO values you simply adjust the WHERE clause. If that works correctly, you can use that with your insert statement to then insert the desired rows.
insert into dbo.ICUNIT (...)
select distinct icu.ITEMNO, 'CTN', '20220509', '22513927', 'ADMIN', 'AU', '1'
from ...
;

Updating a table column using multiple data from another table

I have 2 tables Awards_Nominations and custom_1, and I need to update Awards_Nominations.Add14 column with the concatenations of custom_1.awardNames.
Conditions should have :
Add1 >= GPA
Majors like Add3 or 'AllMajors'
AcademicReq like Add2 or 'High School Student'
Universities like Add4 or 'AllUniversities'
sample Awards_Nominations
sample custom_1
I tried with the update statement inner join but it does not update.
UPDATE [dbo].[Awards_Nominations]
SET Add14=Add14+','+awardName
from [Awards_Nominations] a
inner join custom_1 on right([Add1],3)>=GPA and (Majors like '%'+Add3+'%' or Majors='AllMajors')
and (AcademicReq like '%'+Add2+'%' or 'High School Student' like '%'+AcademicReq+'%') and (Universities like '%'+Add4+'%' or Universities='AllUniversities')
where n_AwardID=4 and ApprovalStatus='final' and Add1<>''
GO
My end goal is to have something like below:
sample updated Awards_Nominations
With an update that matches multiple records, the last update wins. The source column value is not updated for use as input later. (It's sort of like the "inserted" table in a trigger that represents the data before the query.) You want to concatenate data from multiple rows into a single value. There are plenty of examples out there. I prefer XML myself. I will try STRING_AGG the next time I need to do this.
How to concatenate text from multiple rows into a single text string in SQL server?

SQL query based on list from another query

I am trying to build a query that will generate a list of records based on the results of a very similar query.
Here are the details and examples
Query 1: Generate a list if part #'s in a specific location of the warehouse.
Query 2: Use the list of part #'s generated in #1 to show all locations for the list of part #'s, assuming they will be in both the location specified in #1 and other locations.
Query 1 looks like this:
Select
ItemMaster.ItemNo, BinInfo.BIN, ItemDetail.Qty, ItemDetail.Whouse_ID
From
((ItemDetail
Left Join
ItemMaster on ItemMaster.ID=ItemDetail.Item_ID)
Left Join
BinInfo on BinInfo.ID = ItemDetail.Bin_ID)
Where
ItemDetail.Whouse_ID = '1'
And BinInfo.Bin = 'VLM';
Query 2 needs to be almost identical except the ItemMaster.ItemNo list will come from query #1.
Any help here would be great. I don't know if I need to learn Unions, Nested Queries, or what.
make sure that your first query returns the list of ids that you need.
then write the second query with the WHERE id IN (...) syntax:
SELECT * FROM table1 WHERE id IN
(SELECT id FROM table2 WHERE...) -- first query

Access SubQuery: SHOW TOP (count form select query) Table

Is it possible to use a Count() or number from another Select query to SELECT TOP a number of rows in a different query?
Below is a sample of the update query I'm trying to use but would like to take the count from another query to replace "10".
...
WHERE Frames.Package IN (
SELECT TOP 10 Frames
FROM Frames.Package WHERE Package = "100"
ORDER BY Frames.ReferenceNumber
)
So for example, i've tried to do
SELECT TOP SelectQuery.RecordCount Frames
Sample SelectQuery.RecordCount
SELECT COUNT(Frames.Package) AS RecordCount
FROM Frames
HAVING Frames.Package = "100";
Any assistance would be appreciated...
Access does not support using a parameter for SELECT TOP. You must write a literal value into the text of the SQL statement.
From another answer: Select TOP N not working in MS Access with parameter
On that note, your two queries appear to be just interchanging HAVING and WHERE clauses to get the record count. It doesn't seem to be doing anything more, thus why bother with the TOP clause and simply SELECT * FROM Frames WHERE [..]?
Am I missing something?

Change order of columns appearing in results, without changing select order

I have a query where I'm selecting more than 15 things, and thus getting (more than) 15 columns in my results. Some of the things I've selected are big CASE statements. T-SQL of course displays your result in the order than you list things in the SELECT statement.
Is there a way to have the result columns displayed in a different order to help with my review of them, without
a) re-ordering how they were selected (because I'll need to do this every time I want to compare two other columns side-by-side)
i.e. Don't want to change: SELECT a,b,c,d,e,f to SELECT f,d,a,b,c,e
since a-f can each be 5-10 lines of code
b) drag-n-drop column in the results next to each other, because if I want column 2 to be next to column 9 and column 14, and all three to be at the end of the result table, then that'd a lot of dragging to do.
c) knowing the column number of what was selected as opposed to the column name
What I'm looking for is something that resembles:
Select
vi.Name
,vi.Height
,vi.Power
,case when tt.losses < 3
then 'Y'
else 'N'
end as MasteryKen
,tt.blahnum
,vi.blahtext
,vi.blahdate
,vi.blahcalc
,tt.blahflag
,vi.blahflag
,vi.blahcompare
From SenshiVitalInfo vi
Join TatakauTable tt
on vi.namecd=tt.namecd
OrderOutputResults by tt.blahflag, vi.blahflag, *
Does a function to do the last line exist in T-SQL (SQL Server 2008)?
There is no functionality in TSQL to "move" the columns around, other than editing the SELECT list order, this is the best you can do:
SELECT
d.Name
,d.Height
,d.Power
,d.MasteryKen --<<can now move around single lines
,d.blahnum
,d.blahtext
,d.blahdate
,d.blahcalc
,d.blahflag
,d.blahflag
,d.blahcompare
FROM (Select
vi.Name
,vi.Height
,vi.Power
,case when tt.losses < 3
then 'Y'
else 'N'
end as MasteryKen
,tt.blahnum
,vi.blahtext
,vi.blahdate
,vi.blahcalc
,tt.blahflag
,vi.blahflag
,vi.blahcompare
From SenshiVitalInfo vi
Join TatakauTable tt
on vi.namecd=tt.namecd
) d
--ORDER BY ....
You can wrap your existing query inside a derived table, where you can then move the single line columns names all you want. Just make sure that any ORDER BY is moved out of the derived table.
If You are using SSMS, you can view your result set in "results to grid" mode and just drag and drop the column headings to slide the columns around.
No this does not exist.
If you don't like moving the case statements you could put the query into a view that you select from and then you select list will be simplified, but that seems like a waste of effort to me.
I don't think this functionality is part of any SQL variant.
If you are using a SQL IDE to view the result set you might be able to drag the columns you want together, I used to do this in SSMS.
Otherwise Abe's answer is all you can do.

Resources