Running query without intermediate data creation in sql - sql

My query looks like this
CREATE TABLE work_pr.op1 AS
SELECT DISTINCT level1_idnt
,org_sales_price
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01';
CREATE TABLE work_pr.op2 AS
SELECT level1_idnt
,org_sales_price
FROM work_pr.op1
WHERE org_sales_price IS NOT NULL;
CREATE TABLE work_pr.final_op AS
SELECT level1_idnt
,avg(org_sales_price) AS op
FROM work_pr.op2
GROUP BY level1_idnt;
I want the steps to be in same sequence except that I dont want to create work_pr.op1 and the work_pr.op2 tables. How can I shorten this process in sql. I am very new to sql and any help will be greatly appreciated

You can just use nested selects in order to create a single table, the last one:
CREATE TABLE work_pr.final_op AS
SELECT level1_idnt
,avg(org_sales_price) AS op
FROM (
SELECT level1_idnt
,org_sales_price
FROM (
SELECT DISTINCT level1_idnt
,org_sales_price
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01'
) result_set_1
WHERE org_sales_price IS NOT NULL
) result_set_2
GROUP BY level1_idnt;
As #GordonLinoff mentioned, the SELECT can be simplified and you can use the one in his answer.

You can write the query as:
SELECT level1_idnt, AVG(org_sales_price) as op
FROM (SELECT DISTINCT level1_idnt, org_sales_price
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01' AND org_sales_price IS NOT NULL
) l
GROUP BY level1_idnt;
However, it should be unnecessary to have the DISTINCT in the subquery. Normally, the query would be simplified to:
SELECT level1_idnt, AVG(org_sales_price) as op
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01' AND org_sales_price IS NOT NULL
GROUP BY level1_idnt;

Related

How to I return a case record with latest date using SQL

I want a query that returns a record set of the shaded rows from the table above for each unique case_id by the latest data_level_assinged value. I tried something like this:
SELECT case_id, level, date_level_assigned
FROM table
SORT BY case_id, date_level_assigned DESC;
From reading it looks like I need to use an aggregate function like MAX(data_level_assinged) but am not sure how to do this.
You're almost there.
Using MAX is a good approach.
SELECT b.case_id, a.level, b.date_level_assigned FROM tablename a
JOIN
( SELECT MAX(date_level_assigned) as date_level_assigned, case_id
FROM tablename
GROUP BY case_id
) as b
ON a.case_id = b.case_id AND a.date_level_assigned = b.date_level_assigned
You can do it in this way

Query to show all ID's except the ones that have a specific instrument

So I have a table which looks like this:
What would be the best query to exclude every "stuknr" that has atleast 1 "saxofoon" in the "instrumentnaam" column?
To select all stuknr where there is not stuknr with a saxofoon:
SELECT *
FROM table
WHERE stuknr not in (
SELECT stuknr
FROM TABLE
WHERE INSTRUMENTNAAM = ‘saxofoon’)
;
SELECT STUNKR
FROM TABLE
WHERE INSTRUMENTNAAM != ‘saxofoon’;
Here != (or <>, which are equivalent, see this) means "not equal".
You can do this with a NOT IN sub-select
select distinct
YT.stunkr
from
YourTable YT
where YT.stunkr NOT IN ( select distinct stunkr
from YourTable
where InstrumentNaam = 'saxofoon' )
So the sub-select is getting all IDs that DO have saxofoon and the primary select/from is getting where the ID is NOT in the secondary.

In clause of a select but with more than one value to look for

I have a set of results that I query with connect by prior, now I need to check in the where clause of a query if ONE of those results is IN some other set of values(a select * from another table). I'm trying to use 'IN' but I think that that only works when I have one unique value to check for, and not a group of values.
SELECT COUNT('X')
INTO V_COUNT
FROM SIC_NEA_CATFRU
WHERE (SELECT cod_nivel_estr_art
FROM niveles_estr_art
CONNECT BY PRIOR cod_nivel_estr_art_P = cod_nivel_estr_art
START WITH cod_nivel_estr_art = V_COD_NIVEL_eSTR_ART) IN ( SELECT COD_NIVEL_eSTR_ART FROM SIC_NEA_CATFRU);
Would the intersect set operator do? Something like this: first query is your hierarchical query, while the second returns values from the sic_nea_catfru table. If there are any matches, you'll know how many:
SELECT COUNT (*)
INTO v_count
FROM ( SELECT cod_nivel_estr_art
FROM niveles_estr_art
CONNECT BY PRIOR cod_nivel_estr_art_p = cod_nivel_estr_art
START WITH cod_nivel_estr_art = v_cod_nivel_estr_art
INTERSECT
SELECT cod_nivel_estr_art FROM sic_nea_catfru)

Access: query crashes

I have the following query (let's call it Query1) (kindly created here by Erik von Asmuth):
SELECT PARTNERID
,NAME
,FIRST_NAME
,UID
,DATA_R
FROM MY_TABLE
WHERE MY_TABLE.[DATA_R] = (
SELECT MAX(t.[DATA_R])
FROM MY_TABLE AS t
WHERE t.PARTNERID = MY_TABLE.PARTNERID
)
ORDER BY PARTNERID;
MY_TABLE has 20000 records and is a Query (even if the name might suggest the opposite) with the following form:
SELECT [MYTABLE_O].PARTNERID, [MYTABLE_O].NAME, [MYTABLE_O].FIRST_NAME, [MYTABLE_O].[Codice fiscale] AS CF, [MYTABLE_O].Date AS DATA_R
FROM [MYTABLE_O] LEFT JOIN [TO_EXCLUDE] ON [MYTABLE_O].[PARTNERID] = [TO_EXCLUDE].[PARTNERID]
WHERE ((([TO_EXCLUDE].PARTNERID) Is Null));
(I want to exclude some already considered elements that are in Table TO_EXCLUDE).
When I run the query (Query1) MS Access freezes. How can I avoid it/make it more efficient and stable?
I have tried to index in MYTABLE_O both PARTNERID AND DATA_R
You may have to write the result of the subquery:
SELECT PARTNERID, MAX([DATA_R]) AS MAXDATAR
FROM YourQuery
GROUP BY PARTNERID
to a temp table, and then replace in your query
FROM MY_TABLE AS t
with
FROM TempTable AS t

SQL Logic: Finding Non-Duplicates with Similar Rows

I'll do my best to summarize what I am having trouble with. I never used much SQL until recently.
Currently I am using SQL Server 2012 at work and have been tasked with trying to find oddities in SQL tables. Specifically, the tables contain similar information regarding servers. Kind of meta, I know. So they each share a column called "DB_NAME". After that, there are no similar columns. So I need to compare Table A and Table B and produce a list of records (servers) where a server is NOT listed in BOTH Table A and B. Additionally, this query is being ran against an exception list. I'm not 100% sure of the logic to best handle this. And while I would love to get something "extremely efficient", I am more-so looking at something that just plain works at the time being.
SELECT *
FROM (SELECT
UPPER(ta.DB_NAME) AS [DB_Name]
FROM
[CMS].[dbo].[TABLE_A] AS ta
UNION
SELECT
UPPER(tb.DB_NAME) AS [DB_Name]
FROM
[CMS].[dbo].[TABLE_B] as tb
) AS SQLresults
WHERE NOT EXISTS (
SELECT *
FROM
[CMS].[dbo].[TABLE_C_EXCEPTIONS] as tc
WHERE
SQLresults.[DB_Name] = tc.DB_NAME)
ORDER BY SQLresults.[DB_Name]
One method uses union all and aggregation:
select ab.*
from ((select upper(name) as name, 'A' as which
from CMS.dbo.TABLE_A
) union all
(select upper(name), 'B' as which
from CMS.dbo.TABLE_B
)
) ab
where not exists (select 1
from CMS.dbo.TABLE_C_EXCEPTION e
where upper(e.name) = ab.name
)
having count(distinct which) <> 2;
SQL Server is case-insensitive by default. I left the upper()s in the query in case your installation is case sensitive.
Here is another option using EXCEPT. I added a group by in each half of the union because it was not clear in your original post if DB_NAME is unique in your tables.
select DatabaseName
from
(
SELECT UPPER(ta.DB_NAME) AS DatabaseName
FROM [CMS].[dbo].[TABLE_A] AS ta
GROUP BY UPPER(ta.DB_NAME)
UNION ALL
SELECT UPPER(tb.DB_NAME) AS DatabaseName
FROM [CMS].[dbo].[TABLE_B] as tb
GROUP BY UPPER(tb.DB_NAME)
) x
group by DatabaseName
having count(*) < 2
EXCEPT
(
select DN_Name
from CMS.dbo.TABLE_C_EXCEPTION
)