SQL query extraction: same row with same id - sql

I am bit stuck on the following. The data of the table as follows:
sid eid description returncode responsemessage State
1 T-1 200 OK Sent
1 T-1 Helloworld Processed
I cannot use stored procedure, the application only supports a SQL query.
select *
from table
where eid='T-1'
and returncode='200'
and returnmessage='OK'
and state='Sent'
May be something needs to be added here??
Any tips or ideas on how I can achieve this with SQL query?
Update: Oracle Database, I want to retrieve "HelloWorld" from the description column but it should be only retrieved when State=Sent has returncode=200 and responsemessage=ok

I'm not entirely clear on what you are trying to accomplish, but maybe you meant something like this:
select T1.*
from table T1
INNER JOIN table T2
ON T2.SID = T1.sid
where T1.eid='T-1'
and T1.returncode='200'
and T1.returnmessage='OK'
and T1.state='SENT'
AND T2.description IS NOT NULL

I think you can do this using exists:
select t.*
from t
where t.description is not null and t.eid = 'T-1' and
exists (select 1
from t t2
where t2.eid = t.eid and t2.returncode = '200' and
t2.returnmessage = 'OK' and t2.state = 'SENT'
);
You might want to include equality on sid as well, but that is not clear from the question.

Related

Conditional UPDATE for non-related tables in SQLServer 2008

I'm trying to update historicTable (8k records containing employee data) when 2 IDs match (one company id and the other area id) with the tempTable, which is a temporary table with the data I want to update (SUBG_ROT), else (the column stays empty), it should copy data from colx to coly from the same historic table. I was thinking of a JOIN/INNER JOIN but I can't get the structure at all, so I did a stored procedure with a conditional update, but I can't figure out how to call the temporary table. Any hints on the logic/code are appreciated, I'm starting on SQL Server so I'm kinda clueless.
In my mind the code should do:
Update historicTable set SUBG when h.id1 = t.id1 and h.id2 = t.id2 then h.SUBG = t.SUBG else h.id1 = h.SUBG
And this is the code
CREATE PROCEDURE updateHistoric
AS
UPDATE dbo.historicTable
SET SUBG_ROT = CASE
WHEN id1 = temptable.id1 AND id2 = temptable.id2
THEN SUBG_ROT = temptable.SUBG_ROT
ELSE SUBG_ROT = AREA
END
GO
You can try using OUTER APPLY like follownig.
UPDATE t
SET t.subg_rot = CASE
WHEN o.subg_rot IS NOT NULL THEN o.subg_rot
WHEN t.subg_rot IS null then t.area
ELSE t.subg_rot
END
FROM dbo.historictable t
OUTER APPLY (SELECT TOP 1 subg_rot
FROM temptable t2
WHERE t1.id1 = t2.id1
AND t1.id2 = t2.id2)o
Note: Same thing is also possible using LEFT JOIN or sub queries.

Check if a combination of fields already exists in the table

My weakest area of SQL are self JOINS, currently struggling with an issue.
I need to find the latest entry in a table, I'm using a WHERE DATEFIELD IN (SELECT MAX(DATEFIELD) FROM TABLE) to do this. I then need to establish if 3 columns from that already exist in the same TABLE.
My latest attempt looks like this -
SELECT * FROM PART_TABLE
WHERE NOT EXISTS
(
SELECT
t1.DATEFIELD
t1.CODE1
t1.CODE2
t1.CODE3
FROM PART_TABLE t1
INNER JOIN PART_TABLE t2 ON t1.UNIQUE = t2.UNQIUE
)
WHERE t1.DATEFIELD IN
(
SELECT MAX(DATEFIELD)
FROM PARTTABLE
)
)
I think part of the issue is that I can't exclude the unique row from t1 when checking in t2 using this method.
Using MSSQL 2014.
The following query will return the latest record from your table and a bit flag whether a duplicate tuple {Code1, Code2, Code3} exists in it under a different identifier:
select top (1) p.*,
case when exists (
select 0 from dbo.Part_Table t where t.Unique != p.Unique
and t.Code1 = p.Code1 and t.Code2 = p.Code2 and t.Code3 = p.Code3
) then 1
else 0 end as [IsDuplicateExists]
from dbo.Part_Table p
order by p.DateField desc;
You can use this example as a template to address your specific needs, which unfortunately aren't immediately apparent from your explanation.

Run second query if first query does not return any results and return

I am trying to keep this to the minimal table queries to ensure less database usage. I am using Microsoft SQL Server Management Server.
I have a query which will sometimes return nothing depending on the user's current status. If this first query does not return any results, I would like the second query to run.
This is inside of a function and requires returning a single row of column data. I will include the queries with names changed for an example. I will do my own optimization after to make a temp table so the database is not accessed as often. I just need to figure out how to make this work first.
-- Query #1
INSERT #tlbReturn (returnInfo1, returnInfo2)
SELECT TOP(1) returnInfo1, returnInfo2
FROM table1 AS t1a
INNER JOIN table1 AS t1b ON t1a.someData1 = t1b.someData1
AND t1a.someData2 = t1b.someData2
AND t1a.someData3 = t1b.someData3
AND t1a.someData4 = t1b.someData4
INNER JOIN table2 AS t2 ON t2.someData6 = t1b.someData7
AND t2.someData8 = t1b.someData9
WHERE t1a.someData10 = 'value'
AND t1b.someData11 IN ('value1', 'value2')
ORDER BY t1b.someDate DESC;
-- Query #2
INSERT #tlbReturn (returnInfo1, returnInfo2)
SELECT TOP(1) returnInfo1, returnInfo2
FROM table1 AS t1a
INNER JOIN table1 AS t1b ON t1a.someData1 = t1b.someData1
AND t1a.someData5 = t1b.someData5
INNER JOIN table2 AS t2 ON t2.someData6 = t1b.someData7
AND t2.someData8 = t1b.someData9
WHERE t1a.someData10 = 'value'
AND t1b.someData11 IN ('value1', 'value2')
ORDER BY t1b.someDate DESC;
In theory I would like something like,
IF EXISTS(QUERY1) THEN RETURN
ELSE RETURN QUERY2
Check the value of ##ROWCOUNT after the first query.
Do a first select, check ##ROWCOUNT and if it's a zero do a second select

Sql query is slow(exists/joins)

I've got a SQL query to update records. I use 'EXISTS' function but it's very slow. Now I want to change my query with joins.
UPDATE zp
SET ZP.TEST1=NULL,
ZP.TEST2=NULL,
ZP.TEST3=NULL,
ZP.TEST4=NULL,
ZP.TEST5=NULL,
ZP.TEST6=NULL,
ZP.TEST7=NULL,
ZP.TEST8=NULL,
ZP.TEST9=NULL,
ZP.TEST10=NULL,
ZP.TEST11=NULL,
ZP.TEST12=NULL,
ZP.TEST13=NULL,
ZP.TEST14=NULL,
ZP.TEST15=NULL
from TestTable ZP
WHERE NOT(
(ZP.name='I'
AND
surname='S'
OR
addr='S'
AND
ClientID IS NOT NULL)
AND EXISTS(
SELECT * FROM table2 P
WHERE P.OrgID=ZP.OrgID AND
P.CATEGORY='D'
)
)
A slight efficiency improvement would be....
EXISTS(
SELECT 1 FROM table2 P
WHERE P.OrgID=ZP.OrgID AND
P.CATEGORY='D'
Namely 1 rather than *.
But I'm sure that's not the complete solution.

SQL SERVER SELECT sum values

Problem is when I try get sum values from 2 different tables, but using condition from table 3 result are corrupted by wrong sum result . So I tried Select sum() as t1 (select sum()...) as t2 and I want to sum t1 and t2, in this way t1 and t2 result are correct
so there are code
SELECT
SUM(daa.[price]) AS t1,
(
SELECT SUM(dap.[price]) AS suma
FROM fydtr.dbo.[sales] AS dap,
[fydtr].[dbo].[work info] AS di
WHERE YEAR(di.[end of work datetime]) = 2013
AND MONTH(di.[end of work datetime]) = 12
AND di.[state] = 'e'
AND di.[reg. nr.] = dap.[reg. nr.]
) AS t2
FROM [fydtr].[dbo].[work sale] AS daa,
fydtr.dbo.[work info] AS dbi
WHERE YEAR(dbi.[end of work datetime]) = 2013
AND MONTH(dbi.[end of work datetime]) = 12
AND dbi.[state] = 'e'
AND dbi.[reg. nr.] = daa.[reg. nr.]
It gives result
t1 340
t2 509
And I need sum these and get 849 as t3.
What about something like this.
select t1, t2, t1 + t2 t3
from (
the query from your question
) temp
Not completely clear, due to missing input data. But I assume you're searching for something like this:
select sum(sale.pice) as t1
, sum(sales.price) as t2
, sum(sales.price) + sum(sale.price) as t3
from [work info] as info
left outer join [work sale] as sale on (info.state = 'e' and info.[reg. nr.] = sale.[reg. nr.])
left outer join [work sales] as sales on (info.state = 'e' and info.[reg. nr.] = sales.[reg. nr.])
where year(info.[end of work datetime]) = 2013
and month(info.[end of work datetime]) = 12
This depends on the relations between your tables, e.g. in my example, I'm assuming that there's only one entry per [reg. nr.] in all tables. Otherwise you could use "window functions", or UNIONS or CTE's (http://msdn.microsoft.com/en-us/library/ms175972.aspx). You might need to supply more context to get the answer you're searching for.
My given query is probably a little bit cleaner than your query. If that's not an issue, or if my assumption is wrong, then Dan Bracuk's answer helps you out.
And you should probably look at the column names, too. They're a little bit too complex in my opinion :)