Using the result of one query to feed into another query - sql-server

I'm trying to create a compliance rule that checks for a listing of the sys.traces
SELECT id FROM sys.traces
and then use that result to list which trace events have been added to the trace
SELECT DISTINCT(eventid)
FROM sys.fn_trace_geteventinfo(#result from previous query)
I want the result to be just a list of trace ids that I can compare to a set requirement.
I'm obviously new to this and have searched but didn't find anything specifically relevant. I know this is an easy one.

SELECT DISTINCT(eventid)
FROM sys.fn_trace_geteventinfo(SELECT id FROM sys.traces)
SELECT DISTINCT(eventid)
FROM sys.fn_trace_geteventinfo(SELECT top 1 id FROM sys.traces)

Try this query
select distinct info.eventid
from sys.traces as tr
cross apply sys.fn_trace_geteventinfo (tr.id) as info

Related

Getting results from results

I apologize if I don't make much sense but I've tangled my brain up trying to work this out.
I'm trying to obtain a result set using the results from one query but then also hoping to include the previous results within the new query and then somehow group them.
What I have are parent Work order numbers and it’s child work order numbers.
Sadly the system I am using doesn't have the functionality set up yet to simply produce a report that shows all the specific type of work and their linked work.
So I have an initial basic query 1 to find anything that has a "JPNUM like AK0147" and "STATUS NOT IN ('COMPLETE', 'CANCELLED', 'REVIEWED', 'CLOSED')"
The result of the above query 1 will return a result set that includes the column 'WONUM'.
I need to then do a separate search using the column 'PARENT' whereby I return any results that have a number in this column matching any of the WONUMs that were returned in query 1.
I also want to include the results of query 1, probably in query 3, so I can group them together.
How do create write a query that includes my results from query 1 into query 2 and then how do I group them so I have the parent WONUM at the top and it's children work orders underneath, like the final results table I have shown in the attached image?
You could run a select from another select and so on.
I will write you an example:
SELECT WONUM, PARENT.WONUM
FROM (SELECT WONUM, JPNUM
FROM yourTable
WHERE "JPNUM like AK0147"
AND "STATUS NOT IN ('COMPLETE', 'CANCELLED', 'REVIEWED', 'CLOSED')") PARENT
WHERE ...
This way the result of the inner SELECT acts like a temporary table.
There's more than one way to do it, if you're using sql-server, I recommend CTE:
WITH Query1
(
SELECT WONUM, JPNUM
FROM MyTable1
WHERE ...
),
Query2
(
SELECT WONUM, PARENT
FROM Query1 -- You can use Query1, if you want
JOIN MyTable2 ON Query1.JPNUM = ...
WHERE ...
)
-- Final Result:
SELECT WONUM, PARENT
FROM Query2
JOIN Query1 ON ...
JOIN Table3 ON ...
WHERE ...
In this way, you can query using previous query or previous previous query (if needed).

Temp Table with Wild Card

I need to clean up some observations in a table that are inaccurate prior to joining to the after mentioned table, this will avoid duplicate observation output.
I validated that the max(date_value) removes the 9K inaccurate transactions ..... newer transaction were completed which fixed the problem.
The code below, without into #temp, fixes the issue but as soon as I add a temp table, I get a syntax error will not execute, I need like 20 variables out of the table and really don't feel like listing them all, must be a simple syntax or alternative method.
SELECT * INTO #temp FROM db.dbo.table WHERE MAX(date_value);
SELECT a.* INTO #temp
FROM table a
inner join (select id, max(created_at) as max_created
from db.table
group by id) b
on a.id = b.id

SQL Server 2012 Full Text Search match results

I would like to know if there is a way to get the words that were matched from a full-text search using FREETEXT.
For example:
SELECT *
FROM table
WHERE FREETEXT(column_name, 'search term')
I'd like to be able to see which parts of the text in column_name triggered a match with 'search term' since FREETEXT returns records where the searched column are more than just the search term pattern matches as stated here in the FREETEXT/FREETEXTTABLE section.
I know that using FREETEXTTABLE can return the rank and key but I need to know which actual terms triggered a match if it is possible.
Thanks
Disclaimer, I haven't done this -- I'm going from documentation. I'm not sure this gets you what you want, but you can see how the search is tokenized:
from here
After you apply a given word breaker, thesaurus, and stoplist
combination in a query, you can see how Full-Text Search tokenizes the
results by using the sys.dm_fts_parser dynamic management view. For
more information, see sys.dm_fts_parser (Transact-SQL).
I'm guessing if you want to know which part (token) caused the match -- you'll likely need to run the search on the individual tokens and compare the result sets to see which token or tokens (search term/s) caused the given match.
You could try LIKE
SELECT *
FROM table
WHERE column_name like ('%search term%')
You will need Split String function
Then you will to create one Temporary table which is permanent.
Like in my example StagingFreeText (define data type as per requirement)
create table StagingFreeText (col varchar(100) not null)
Then create Full Text Index on StagingFreeText
In the start of script always truncate table
Truncate table StagingFreeText
Then insert the result into StagingFreeText
;with CTE as
(
SELECT *
FROM table
WHERE FREETEXT(column_name, 'search term')
)
insert into StagingFreeText(col)
SELECT value
FROM CTE
cross apply(select value from dbo.split_string(column_name,' '))ca
Again apply search condition like above
SELECT *
FROM StagingFreeText
WHERE FREETEXT(col, 'search term')
Note : My script is not tested but idea is very much clear.
Or if you don't want to Create another Free Text index on StagingFreeText then you can split the Search Term in #temp table and join StagingFreeText with #temp table
If you want to full text search another way then use plenty of method few are written below
Select * from Table
Where Column_Name Contains('some thing')
Select * from Table
Where Column_Name exists ('some thing')
Select * from Table
Where Column_Name in ('some thing')
Select * from Table
Where Column_Name =(some) ('some thing')

select list based on select query in apache zeppelin

i am using apache zeppelin version 0.6.
i have the following hive query
select certificate_name,count(*) from student_withdraw
now i want to have a where clause which is represented to the end user as a select list. the inner query is like below
select certificate_name,count(*) from student_withdraw where lecturer_name in (select distinct lecturer_name from student_withdraw)
now the default notation to have a select list is "${item=A,A|B|C}"
i tried to have it like below
%jdbc(hive)
select certificate_name,count(*) from student_withdraw where lecturer_name = "${item=Null,select distinct lecturer_name from student_withdraw}" group by certificate_name
but cannot fetch the distinct lecturers in the select list. all is shown in the select list is the query.
how can i select the distinct lectures for the select list?
thank you
Assumption
Your scenario looks involving dynamic forms on Zeppelin. I can agree with your logic yet dynamic forms won't execute any SQL, or HiveQL, then pass the result as an option onto a page, merely exactly what you typed.
I assume your installation of Zeppelin includes all interpreters, the table is a managed native table on Hive, and the selection of lecturers for end users is necessary.
Solution
If the number of unique lecturer names is not much, like below 10, just typed them all manually in the select form of the query.
SELECT certificate_name, COUNT(*)
FROM student_withdraw
WHERE lecturer_name = ${item=nameA, nameA|nameB|nameC}
GROUP BY certificate_name
Otherwise, you may consider composing the string of the whole lecturer names first, then copying and pasting the outcome into the select form of the query.
Something like the following:
%pyspark
from pyspark.sql import HiveContext
hc = HiveContext(sc)
student_withdraw = hc.table("student_withdraw")
student_withdraw.registerTempTable("student_withdraw")
lecturer_list = student_withdraw.sql('SELECT DISTINCT lecturer_name FROM student_withdraw').rdd.map(r => r(0)).collect()
lecturer_names = '|'.join(lecturer_list)
print(lecturer_names)
 
%jdbc(hive)
SELECT certificate_name, COUNT(*)
FROM student_withdraw
/*the second argument in the select form is copied from the result of the previous execution*/
WHERE lecturer_name = ${item=nameA, nameA|nameB....|nameY|nameZ}
GROUP BY certificate_name

TOP clause in SQL server returns more records than specified

TOP clause in SQL server(I tried this in w3schools.com website) gives more records than specified when used with order by clause. This is the query I used:
select TOP 1 * from orders left join customers on
orders.customerID=customers.customerID order by EmployeeID desc
Please visit this link for my result: https://i.stack.imgur.com/xg7sV.jpg
Instead, this query returns 6 records. Is this how it is supposed to work?
Read the ENTIRE screen. And obviously there is something terribly wrong with their site.
The JOIN part throws you off. Try something like this instead:
select TOP 1 * from orders a
outer apply (select top 1 * from customers where customerID = a.customerID) b
order by a.EmployeeID desc
Try to order the query by name, address, by the order date or whatever that doesn't REPEAT like the EmployeeID. Souns like a very very dumb solution but it worked for me in an Access database with DESC counts.
Looks like if in orders the values repeat the sql returns more than needed... i really don't know why but it worked for me!
Try it!

Resources