SQL Query... I'm new so this is probably easy - sql-server

I can write simple SELECT statements for my SSRS reports but I have run into a wall trying to figure out how to do this query and I'm stumped. I have a table, and it has an entry in it showing me that a particular process is done. The process is Operation_Seq_NO 60 and the QTY_GOOD is 1. There IS NO ENTRY for operation_seq_no with an 80 so it goes on the report. As soon as an 80 entry hits the table, it needs to go off the report. Sounds simple but totally got me stumped. I attached a pic or it in tabular format to maybe help someone understand the issue.

You can use not exists() or not in() to filter rows that have a corresponding row with operation_sec_no = 80 like so:
using not exists():
select *
from labor_ticket as t
where not exists (
select 1
from labor_ticket as as i
where t.transaction_id = i.transaction_id
and i.operation_sec_no = 80
)
or with not in():
select *
from labor_ticket as t
where transaction_id not in (
select transaction_id
from labor_ticket as i
where i.operation_sec_no = 80
)

Related

How to find rows in ms-sql with another rows' value followingly?

I have created an Sql table to trace objects' operation history. I have two columns; first one is the self tracing code and second tracing code is the tracing code for the code coming from source object to target. I created this to be able to look up the route of operations through the objects. You can see the tracing sample table below:
I need to create an sql code to query to show all the route in one table. When I first select the self code, it will be the incoming code for previous rows. There may be more than one incoming code to self and I want to be able to trace all. And I want to reach end until my search is null.
I tried select query like below but I am so new sql and need your help.
SELECT [TracingCode.Self],
[TracingCode.Incoming],
[EquipmentNo]
FROM [MKP_PROCESS_PRODUCT_REPORTS].[dbo].[ProductionTracing.Main]
WHERE [TracingCode.Self] = (SELECT [TracingCode.Incoming]
FROM [MKP_PROCESS_PRODUCT_REPORTS].[dbo].[ProductionTracing.Main]
WHERE [TracingCode.Self] = (SELECT [TracingCode.Incoming]
FROM [MKP_PROCESS_PRODUCT_REPORTS].[dbo].[ProductionTracing.Main]
WHERE [TracingCode.Self] = (SELECT [TracingCode.Incoming]
FROM [MKP_PROCESS_PRODUCT_REPORTS].[dbo].[ProductionTracing.Main]
WHERE [TracingCode.Self] = '028.001.19.2.3')));
To do this kind of parent/child thing to any level without explicitly coding all levels you need to use a recursive CTE.
More details here
https://www.red-gate.com/simple-talk/sql/t-sql-programming/sql-server-cte-basics/
Here is some test data and a solution I came up with. Note that three records actually match 028.001.19.2.3
If this doesn't do what you need please explain further with sample data.
DECLARE #Sample TABLE (
TC_Self CHAR(14) NOT NULL,
TC_In CHAR(14) NOT NULL,
EquipmentNo INT NOT NULL
);
INSERT INTO #Sample (TC_Self, TC_In, EquipmentNo)
VALUES
('028.001.19.2.3','026.003.19.2.2',96),
('028.001.19.2.3','026.001.19.2.2',96),
('028.001.19.2.3','026.002.19.2.2',96),
('028.001.19.2.2','026.002.19.2.1',96),
('028.001.19.2.2','026.002.19.2.1',96),
('028.001.19.2.1','026.002.19.1.1',96),
('026.003.19.2.2','024.501.19.2.5',117),
('024.501.19.2.5','024.501.19.2.6',999),
('024.501.19.2.6','024.501.19.2.7',998);
WITH CTE (RecordType, TC_Self, TC_In, EquipmentNo)
AS
(
-- This is the 'root'
SELECT 'Root' RecordType, TC_Self, TC_In, EquipmentNo FROM #Sample
WHERE TC_Self = '028.001.19.2.3'
UNION ALL
SELECT 'Leaf' RecordType, S.TC_Self, S.TC_In, S.EquipmentNo FROM #Sample S
INNER JOIN CTE
ON S.TC_Self = CTE.TC_In
)
SELECT * FROM CTE;
Also please note that most of the time to generate this answer was taken in generating the sample data to use.
In future when asking questions, people are far more likely to help if you post this sample data generation yourself

Merge statement optimization

I have a two tables in SQL Server, in which one is the source for a MERGE operation into another.
The source table has 30Mil Records
The Target table has 180Mil Records. Both tables have 227 columns.
I do have SSIS, but I'm told in this case, a MERGE statement is the better option. Below is a shortened version of it:
;WITH MySource as (
SELECT * FROM [STAGE].[dbo].[STAGE_TABLE]
)
MERGE [EDW].[dbo].[TARGET_TABLE] AS MyTarget
USING MySource
ON MySource.[ID_FIELD] = MyTarget.[ID_FIELD]
AND MySource.[LoadDate] >= MyTarget.[LoadDate]
WHEN MATCHED THEN UPDATE SET
<<Target Column>> = MySource.<<Source Colums>> --227 columns
WHEN NOT MATCHED THEN INSERT
(
[ID_FIELD],
[LoadDate],
<<225 Other Columns>>
)
VALUES (
MySource.[ID_FIELD],
MySource.[LoadDate],
MySource.<<225 other columns>>
);
The only changes I made to the script above is truncating the list of columns to keep the code block here short.
My Problem is that I am getting hung on the execution. The profile screen shows a CXPACKET suspension with the error: cwaitpipenewrow, node=2.
How do I troubleshoot this? Thank you.
Seems like CXPACKET and suspended state means that some threads which have completed are logging that other thread's state which have not completed yet.
Please check here. The query need to update upto 1 Billion values in the table. hence it would be slow running queries.
https://dba.stackexchange.com/questions/96346/cxpacket-suspended-and-null-wait-type
https://www.sqlshack.com/troubleshooting-the-cxpacket-wait-type-in-sql-server/
Hope these articles might help you debug.

SQL Server - Multiple select queries hit performance

Recently I ran into an issue where we have multiple concurrent client requests causing performance issue in db. I tried the test scenario and as it turned out, when I run SELECT queries (same query) 6 to 7 times (gets worse with more), It degrades the performance and execution takes a lot of time. However I tried this one
SELECT TOP (100) COUNT(DISTINCT([Doc_Number])) AS "Expression"
FROM (
SELECT *
FROM "dbo"."Dummy_Table" "table_alias"
WHERE ((CAST("table_alias"."ID" AS NVARCHAR)) NOT IN
(
SELECT "PrimaryKey" AS ExceptionKey
FROM dbo.exceptions inner_exceptionStatus
LEFT JOIN dbo.Workflow inner_workflowStates ON
(inner_exceptionStatus."Status"= inner_workflowStates."UUID" AND
inner_exceptionStatus."UUID"= 'CA1662D6-73A2-4692-A765-E7E3EDB66062')
WHERE ("inner_workflowStates"."RemoveFromRecordSet" = 1 AND
"inner_workflowStates"."IsDeleted" = 0) AND
("inner_exceptionStatus"."IsArchived" IS NULL OR
"inner_exceptionStatus"."IsArchived" = 0)))) wrapperQuery
The query when runs alone takes around 1sec execution time. But If we runs it in parallel, for each query it takes up a wried amount of time of leads to timeout.
The only thing bothers me here is that SELECT query should be non-blocking and even with shared lock, then need to get along easily.
I am not sure if there is anything wrong in the query that adds up the situation.
Any help is deeply appreciated !!
Try this way
SELECT Count(DISTINCT( [Doc_Number] )) AS Expression
FROM dbo.Dummy_Table table_alias
WHERE NOT EXISTS (SELECT 1
FROM dbo.exceptions inner_exceptionStatus
INNER JOIN dbo.Workflow inner_workflowStates
ON ( inner_exceptionStatus.Status = inner_workflowStates.UUID
AND inner_exceptionStatus.UUID = 'CA1662D6-73A2-4692-A765-E7E3EDB66062' )
WHERE inner_workflowStates.RemoveFromRecordSet = 1
AND inner_workflowStates.IsDeleted = 0
AND ( inner_exceptionStatus.IsArchived IS NULL
OR inner_exceptionStatus.IsArchived = 0 )
AND table_alias.ID = PrimaryKey)
Made couple of changes.
Changed NOT IN to NOT EXISTS
Removed the convert in "table_alias"."ID" because it will avoid using any index present in "table_alias"."ID" column. If the conversion is really required then add it.
Removed Top (100) since there is no Group By it will return a single record as result.
Still if the query is running slow then you need to post the execution plan and make sure the statistics are up-to-date
You can simplyfy your query like this :
SELECT COUNT(DISTINCT(Doc_Number)) AS Expression
FROM dbo.Dummy_Table dmy
WHERE not exists
(
SELECT *
FROM dbo.exceptions ies
INNER JOIN dbo.Workflow iws ON ies.Status= iws.UUID AND ies.UUID= 'CA1662D6-73A2-4692-A765-E7E3EDB66062'
WHERE iws.RemoveFromRecordSet = 1 AND iws.IsDeleted = 0 AND (ies.IsArchived IS NULL OR ies.IsArchived = 0)
and dmy.ID=PrimaryKey
)
Like prdp say :
Changed NOT IN to NOT EXISTS
Removed the convert in "table_alias"."ID" because it will avoid using any index present in "table_alias"."ID" column. If the conversion is really required then add it.
Removed Top (100) since there is no Group By it will return a single record as result.
I add :
Remove you temporary table wrapperQuery
You can use INNER JOIN because into where you test RemoveFromRecordSet = 1 then you remove null values.
Remove not utils quotes ,brackets and parenthèses into where clause

limiting results in sybase ASE between a particular range

I have a search screen which allows the user to search information and it populates a grid. Some of the search results are returning a huge amount of data. I am trying to create a paging grid so that I only bring from the store procedure 10 or 20 results at a time. (I already have a paging grid in the UI)
I am trying to do something like this:
select * from wl_eval limit 1, 20
The query above will return only the first 20 records. How would I be able to accomplish that in Sybase ASE? Unfortunately, for my client project we are using Sybase. I know that in other database engines we could have used the query I mention above. I also know we can use SET ROW COUNT 20 but this wont work if I want a particular range, say from 30 to 50.
Any thoughts?
Add TOP numberofrecords you want to return
DECLARE #intStartRow int;
DECLARE #intEndRow int;
SET #intStartRow = (#intPage -1) * #intPageSize + 1;
SET #intEndRow = #intPage * #intPageSize;
WITH wl_eval AS
(SELECT field,
ROW_NUMBER() OVER(ORDER BY intID DESC) as intRow,
COUNT(intID) OVER() AS intTotalHits
FROM tblBlog)
SELECT field, intTotalHits FROM wl
WHERE intRow BETWEEN #intStartRow AND #intEndRow
SELECT TOP 20 <column list>
FROM YourTable
ORDER BY <list>

TFS 2008: Query Changesets by User and export information to Excel

Doesn't seem to be a question or answer about this. I need to use TFS2008 to query a user's changesets and export the results to Excel.
The catch is that I not only need changeset number, user, and date checked in, but I also need the files affected by the checkin. It's worth nothing that I have a co-worker who has presented the results of a similar query he did a while ago, but he cannot remember how it was done.
I've used Ctrl+G from Source Control Explorer to query changesets, but this dialog will not allow me to export to Excel and will not show me the files affected unless I double-click the changeset. It would be very labor-intensive to try to write this all by hand by clicking through dialog windows. Maybe there's a way to do it through the Work Item Query utility? Any help would be appreciated.
The following is an example of the format I need:
Thanks.
Hopes this might help you
SELECT TOP 10
V.ChildItem AS [File Modified],
V.Command AS [Check-In-Action],
V.ParentPath AS [Modified File Path],
CS.ChangeSetId,
CS.CreationDate AS [Date]
FROM tbl_Changeset CS
INNER JOIN tbl_Identity I ON I.IdentityID = CS.OwnerID
INNER JOIN tbl_Version V ON V.VersionFrom = CS.ChangesetID
ORDER BY CS.CreationDate DESC
Here V.Command stands for
* Edit = 2
* Type = 4
* Add folder = 5
* Add file = 7
* Rename = 8
* Rename,edit = 10
* Delete = 16
* Delete,rename = 24
* Undelete = 32
* Undelete,edit = 34
* Branch = 68
* Branch,delete = 84
* Merge = 128
* Merge, edit = 130
* Merge,type,edit = 134
* Merge, rename, edit = 138
* Merge,delete = 144
* Merge,delete,rename = 152
* Merge,undelete = 160
* Merge,undelete,edit = 162
* Merge,branch = 196
* Merge,branch,edit = 198
I don't think you can build a query from VS interface that would return such a result set. Your best bet would be to query databases directly.
The name of files might not be found in TFS warehouse because it is too much of a detail to be contained in the warehouse so you might have to query the actual TFS database directly. It is worth noting here that "accessing TFS DB directly" is something neither recommended nor supported/documented by Microsoft, but you gotta do what you gotta do. (Be careful, never ever change anything in the DB)
I've tried building a sample query for you but I am using TFS2010. Both DB and warehouse schemas have changed dramatically in TFS 2010 so my query won't be any help to you.
If you manage to build a query, you can run it through Excel and get results directly into Excel.

Resources