Transact SQL :: Pull Records From 3 Tables Using Joins Or Subquery?
Sep 14, 2015
I have 3 tables.
Table 1:
ID Name Description
1 ABc xyz
2 ABC XYZ
Table 2:
RoleID Role
1 Admin
2 QA
Table 3:
ID RoleID Time
1 1 09:14
2 1 09:15
1 2 09:16
Now I want all the records which belongs to RoleID 1 but if same ID is belongs to RoleID 2 than i don't want that ID.From above tables ID 1 belongs to RoleID 1 and 2 so i don't want ID 1.
View 4 Replies
ADVERTISEMENT
Aug 7, 2015
I'm trying to pull all records from one table and just a single record from another. I have this join, (see below). It works ok, but the problem is if a blog record doesn't have a corresponding image record it doesn't return. The end result should be the blog record and a single corresponding image record. But always a blog record.
SELECT
[Blogs].[ID],
[Blogs].[BlogTitle],
[Blogs].[BlogType],
[Blogs].[BlogText],
[code]...
View 6 Replies
View Related
Jun 16, 2015
I am looking to pull all records for current & previous calendar year in one query. I know how to pull the current calendar year, but how would I pull current & previous?
select id, list_date
from tableA
where list_date > DATEADD(year,-1,GETDATE())
View 5 Replies
View Related
Sep 2, 2015
updating the # of Payer from below query to match with the # of rows for each payer record. See the Current and desired results below. The query is currently counting the # of rows for all payers together and updating 3 as # of payers. I need it to count # of rows for each payer like shown inDesired result below. It should be showing 1 for first payer and 2 for 2nd & 3rd based on # of times each payer is repeated..
SELECT b.FILING_IND, b.PYR_CD, b. PAYER_ID, b. PAYER_NAME,a.CLAIM_ICN,
(Select Count(*) From MMITCGTD.MMIT_CLAIM a, MMITCGTD.MMIT_TPL b , MMITCGTD.MMIT_ATTACHMENT_LINK c where a.CLAIM_ICN_NU =
c.CLAIM_ICN and b.TPL_TS = c.TPL_TS and a.CLAIM_TYPE_CD = 'X'
[Code] ....
Current Result
FILING_IND
PYR_CD
PAYER_ID
PAYER_NAME
CLAIM_ICN
#_OF_PAYER
[code]....
View 4 Replies
View Related
May 24, 2006
When calling the method below, if I use the SQL in red, the Pull method populates my data correctly. But, If I use the sql in Green, I get an errror message. I have set breakpoints and un the SQL that is returned from the sql statement is green, and it returns records. What gives? Are Joins not allowed?
public void GetDiagnosisList()
{
// Connection string to SQL Server 2000
string rdaOleDbConnectString = "Provider=sqloledb; Data Source=WORKPC;Initial" +
" Catalog=database;User Id=username;Password=password";
// string SQLGet = "SELECT tblLUDiagnosis.strDiagnosisCode, tblLUDiagnosis.strDiagnosisDesc FROM tblLUDiagnosis" +// " INNER JOIN tblPatientEpisode ON tblLUDiagnosis.strDiagnosisCode = tblPatientEpisode.strPrimaryDiagnosis" +// " WHERE tblPatientEpisode.intHospitalID =" + intHospitalID;
string SQLGet = "SELECT TOP 15 tblLUDiagnosis.strDiagnosisCode, tblLUDiagnosis.strDiagnosisDesc FROM tblLUDiagnosis";
SqlCeRemoteDataAccess rda = new SqlCeRemoteDataAccess();
try
{
rda.InternetUrl = "http://WORKPC/SQLCE/sscesa20.dll";
rda.LocalConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;" + CONN_STRING;
rda.Pull("tblLUDiagnosis",SQLGet,rdaOleDbConnectString, RdaTrackOption.TrackingOnWithIndexes, "ErrorTable");
MessageBox.Show("Diagnosis Synchronized");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
View 1 Replies
View Related
Feb 8, 2001
Hello,
I am in the process of debugging a fairly regular SQL statement. I want to simplify the SQL as much as possible for debugging. What I want to know is ... Is it reasonable to replace the return value of a sub query based on a self join. I thought this was legitimate, but it returns a different row count for each.
Here is what I am doing:
SELECT COUNT(DISTINCT(RELATIONSHIPNAME)) AS NUMRELS
--INTO boi.dbo.TBL_PERMGRADETEAMSUMMRELS
FROM CLIENT C, RELATIONSHIP R, PERMISSION P,REL_GRADEHISTORY G, REL_TEAMHISTORY T, TEAM A
WHERE C.RELATIONSHIPID=R.RELATIONSHIPID
AND G.RELATIONSHIPID=R.RELATIONSHIPID
AND C.CLIENTID=P.CLIENTID
AND T.TEAMID=A.TEAMID
AND R.RELATIONSHIPID=T.RELATIONSHIPID
AND A.REPORTINCLUDE = 'Y'
AND P.CHANGEDATE = (SELECT MAX(CHANGEDATE) FROM PERMISSION P1
WHERE P1.CLIENTID=C.CLIENTID
AND P1.CHANGEDATE <= '01/05/01'
AND P1.TYPE=P.TYPE)
I wanted to simplify the first subquery so I ran it independently and it recieved:
2000-11-17 00:00:00.000
Changed SQL:
SELECT COUNT(DISTINCT(RELATIONSHIPNAME)) AS NUMRELS
--INTO boi.dbo.TBL_PERMGRADETEAMSUMMRELS
FROM CLIENT C, RELATIONSHIP R, PERMISSION P,REL_GRADEHISTORY G, REL_TEAMHISTORY T, TEAM A
WHERE C.RELATIONSHIPID=R.RELATIONSHIPID
AND G.RELATIONSHIPID=R.RELATIONSHIPID
AND C.CLIENTID=P.CLIENTID
AND T.TEAMID=A.TEAMID
AND R.RELATIONSHIPID=T.RELATIONSHIPID
AND A.REPORTINCLUDE = 'Y'
AND P.CHANGEDATE = '17-11-2000'
I therefore put '17-11-2000' into the location of the first subquery ( A convert to varchar of the subquery result gave nov 17 2000).
The new query with the hardcoded date returns 9 rows, the older one returned 117.
Can anyone explain please?
Thanks
Lenin.
View 2 Replies
View Related
Oct 11, 2015
I want to know one small query..
id Name
1 hi
2 how
3 are
4 you
6 can
7 do
8 not
9 did
10 to
I deleted some records now my table have below mentioned rows..
id Name
1 hi
2 how
4 you
6 can
8 not
10 to
I want to know the missing records in my table.
OUTPUT IS. 3,7,9
how can i do that using sql query.
View 11 Replies
View Related
Sep 29, 2015
I need to compare records between two tables. There is no ID in the tables to do a simple join between them. So, what I'm looking for is: get the first record from table1 and read all record from table2 and give me back the most similar record. The String Distance is a predefined function.
Select a.table1
,b.table2
from table1 a, table2 b
where StringDistance (''a.table1,'b.table2') >90
View 4 Replies
View Related
Jan 18, 2008
I have a query similar to the following. The intent of this query is to retrieve the top 6 records meeting the specified criteria (LOGTYPENAME = 'Process Status Start' OR LOGTYPENAME = 'Process Status End' ) based on most recent dates. Please keep in mind that I expect to return up to 6 records for each unique LogProcessName. This could be thousands of different LogProcessNames with up to 6 records for each.
1) The table I am executing against currently is very large in size and thus takes a long time to execute against. It would seem there must be a more efficient query to get the results I am looking for?
2) CTE doesn't work on SQL 2000. I need a query that does.
3) I cannot modify the database itself in the process.
;WITH cte AS (
SELECT [LogProcessName], [LogBody], [LogDate], [LogGUID], row_number()
OVER(PARTITION BY [LogProcessName]
ORDER BY [LogDate] DESC)
AS RN
FROM [LOGTABLE]
WHERE [LogTypeGUID] IN (
SELECT LogTypeGUID
FROM LOGTYPE
WHERE LogTypeName = 'Process Status Start'
OR LogTypeName = 'Process Status End' ) )
SELECT *
FROM cte
WHERE RN = 1 OR RN = 2 OR RN = 3 OR RN = 4 OR RN = 5 OR RN = 6
ORDER BY [LogProcessName] DESC, [LogDate] DESC
Does anybody else have any idea that would yield the results that I am looking for and take into account items 1-3 above?
Thanks in advance.
View 4 Replies
View Related
Aug 30, 2015
This is a bit lengthy, but lets say we have three tables
a) tblSaleStatementCustomer
b) tblCreditors
c) tblReceiptDue
which shows records like below
Table 1 - tblSaleStatementCustomer
ID CustomerName VoucherType Outbound Inbound CustomerType
----------------------------------------------------------------------------------------------
1 ABC Sales 10000 0 Dealer
2 MNC Sales 9000 0 Dealer
3 MNC Sales 4000 0 Dealer
Table 2 - tblCreditors
ID Name OpeningBalance
----------------------------------------------------------------------------------------------
1 ABC 20000
2 MNC 15000
3 XBM 18000
4 XYZ 12000
View 2 Replies
View Related
Jun 18, 2015
i have 3 tables names parent, child1, child2 parent has 1 record, child1 has 2 record and child 3 has 3 records the script
select Parent.*,child1.f1,child2.f2 from child1 inner join Parent on parent.id =child1.id
inner join child2 on child1.id =child2.id
running above query gives me sixes rows but i want only all rows of childs but not their Cartesian products
Object: Table [dbo].[Parent] Script Date: 06/18/2015 17:33:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Parent](
[id] [int] NOT NULL,
[code]....
View 8 Replies
View Related
Aug 30, 2015
Lets say we are executing this query below to retrieve each customer and the amount associated to a table
"INSERT INTO tblReceiptDue (Dealer, Amount) SELECT CustomerName, SUM(CASE WHEN VoucherType = 'Sales' then Outbound ELSE - Inbound END) AS AMOUNT from
tblSaleStatementCustomer WHERE CustomerType = 'Dealer' GROUP BY CustomerName"
Which display the data like below
DEALER AMOUNT
------------------------------------------------
ABC 2000
XYZ 1000
However I have one more table TABLE2 which contains two columns
DEALER OPENING
-------------------------------------------------------
ABC 5000
XYZ 7000
I want to modify my query in such a way that AMOUNT column should also add
OPENING from TABLE2 So that I must get the result like below
DEALER AMOUNT
------------------------------------------------
ABC 7000
XYZ 8000
View 10 Replies
View Related
Aug 11, 2005
SQL Server 2000Howdy All.Is it going to be faster to join several tables together and thenselect what I need from the set or is it more efficient to select onlythose columns I need in each of the tables and then join them together?The joins are all Integer primary keys and the tables are all about thesame.I need the fastest most efficient method to extract the data as thisquery is one of the most used in the system.Thanks,Craig
View 3 Replies
View Related
Nov 5, 2015
I have a table that i'm trying to pull the first transaction and last transaction per prodid. The first transaction, the ctrid should be 'TOPPEntry'.
sample raw data result
prodid--------lineid------itemid---------ctrid----------createddate--
=================================================================
TOP02296228--Line15-----TTC3071-IR------TOPPEntry------2015-01-03 07:45:31.000--input
TOP02296228--Line15-----TTC3071-IR------TOPCBFG--------2015-01-07 16:18:26.000--fg--done processing
TOP02296229--Line15-----TTC3071-IR------TOPPEntry------2015-01-04 07:45:31.000--input
TOP02296229--Line15-----TTC3071-IR------TOPLens--------2015-01-05 12:12:31.000--wip--wip means still in process
TOP02296230--Line15-----TTC3071-IR------TOPPEntry------2015-01-05 08:45:31.000--input
TOP02296230--Line15-----TTC3071-IR------TOPCBSCP-------2015-01-06 14:18:42.000--scrap--done processing
[code]...
View 12 Replies
View Related
Jun 23, 2012
I need to show the count that occurred during the previous 30min. I've been told the following query doesn't work.
SELECT COUNT(*) FROM sampledata
WHERE (id = 254 AND sub_id = 731) AND (sampledate >= DATEADD(mi, -30, GETDATE()))
View 5 Replies
View Related
Apr 21, 2015
I have two tables and I am trying to pull a value closest to another date. There could be instances where the Eval_date in TableA matches the date in TableB so how would that be handled?
TableA
PA_IDEval_Date
12015-01-08 00:00:00.000
22015-01-25 00:00:00.000
TableB
IDPA_IDDate Stat
112015-01-15 00:00:00.000 14
222015-01-28 00:00:00.000 8
312015-01-16 00:00:00.000 2
422015-01-029 00:00:00.000 3
512015-01-09 00:00:00.000 11
612015-03-14 00:00:00.000 14
Expected Results
PA_IDDate Stat
12015-01-09 00:00:00.000 11
22015-01-28 00:00:00.000 8
View 8 Replies
View Related
Dec 5, 2007
How to pull null (empty) records from SQL database,
what query am I suppose to use to get result
help me
thank you
maxs
View 4 Replies
View Related
Jun 10, 2015
I need to pull dates from a DB2 database via TSQL (Linked server - IBM DB2 for i IBMDASQL OLE DB Provider) and compare it to today for a less than or greater than type comparison.
Database: DB2, Customer information housed here
Columns:
UTOFMM - Month (2 character, numeric)
UTOFDD - Day (2 character, numeric)
UTOFYY - Year (2 character, numeric. Problem: years from 2000 to 2009 are stored as 0, 1, 2, ... etc)
UTOFCV - Century Value (2 char, numeric. 0 = before 2000, 1 = in or after 2000)
I need to concatenate the date to be "sql" friendly, and then compare to today's date. It's to find any customer with date values in the fields above, and then differentiate between dates before today and after today.Here is the snippet of what I'm trying to fix. This portion of a nightly job is just checking for <u>any</u> value in the UTOFMM column of the current record.
Add Customer ID
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0
GO
View 4 Replies
View Related
Jan 30, 2014
I have the following table:
SEQ DATE
123 JAN-01-2013
123 JAN-01-2013
124 FEB-28-2013
125 MAR-05-2013
125 MAR-05-2013
125 MAR-05-2013
125 MAR-05-2013
I need a script to pull the above records ONLY if the date repeats more than one within the same SEQ number. The proper script would output as follows:
SEQ DATE
123 JAN-01-2013
123 JAN-01-2013
125 MAR-05-2013
125 MAR-05-2013
125 MAR-05-2013
125 MAR-05-2013
View 2 Replies
View Related
Nov 23, 2015
I have the below data and want to only show records where Response Column has Max date for the commencement date and expiry date under questions column.. For example for tenantcode 52090 the highest Tab value is 2 but this is not correct as there is no associated value in response.
We need to compare all the commencement and lease expiry dates and show only the commencement and lease expiry with the recent dates. Null should be ignored Instead of using Max Tab or Max Modified date would the below logic work? Not sure how to script this.
1. Filter to find Questions containing "Expiry Date"
2. summarise to find the max expiry date per Tenant Code
3. find which records have that maximum expiry
4. join again to find the commencement date
5. union the records from (3) and (4)
6. cross tab
Declare @rent Table
(
TenantCode CHAR(6)
,HHMID CHAR(5)
,Tab CHAR(4)
,FieldNo CHAR(4)
,FieldRowCHAR(10)
[code]....
View 29 Replies
View Related
Aug 18, 2015
I have the following stored proc that I need to pull InsuranceID specific rows when @InsuranceID > 0 is sent. Below is the code and I think the issue is in the 2nd WHERE condition.
ALTER PROCEDURE [dbo].[ms_selJobSetupSelections]
(@ActiveOnlybit = 1,
@InsuranceIDint = 0)
AS
BEGIN
SELECT J.JobSetupID
,J.JobSetupText
[code]....
View 21 Replies
View Related
Aug 6, 2007
Hi Gurus,
I have a table having sales records and there are more than one record per one customer. The sales table has a reference number like below.
CustomerID
Sales_Ref
2
H_1123
2
H_2344
2
H_4322
I need to do a query and generate the following query.
CustomerID Ref
2 H_1123,H_2344,H_4322
Could someone help me on this.
Thanks.
Cheers,
Vijay
View 3 Replies
View Related
Apr 30, 2015
What is wrong in this query am getting incorrect syntax near ','.error. I am using sql server 2014
DELETE ab, b
FROM Authors AS a INNER JOIN AuthorArticle AS ab ON a.AuthID=ab.AuthID
INNER JOIN Articles AS b ON ab.ArticleID=b.ArticleID
WHERE AuthorLastName='Tom';
View 4 Replies
View Related
Oct 22, 2015
(select SUM(sales.Total) from sales where StudentHist.Curdate = max(sales.curdate)) AS 'Balance'Iam trying to write a subquery to calculate the total amount of sales until the Curdate in studenthist equals the Curdate in sales table..how to write this query??
View 11 Replies
View Related
Jul 29, 2015
with c1 As (
select 1 As '1' , 2 As '2' , 3 As '3'
)
, c2 As (
select 4 As '4', 5 As '5', 6 As '6'
union all
select 1 , 2 ,3 from c1 -- >>>>> select from c1 here
) select * from c2
union all
select * from c1 -- >>>>>> and select from c1 here
According to the query above , I try to reuse the subquery by put the subquery into 'with cte' name (c1) then i select this 2 times .
if I do this way , how many time this subquery (c1) execute ?
if 1 time then this is the right way to reuse this subquery .
if 2 times , it is not then what should i do to reuse this subquery ?
View 3 Replies
View Related
Apr 27, 2015
I have a table which is called PneumoniaCareBundleDiagnosisCodes with the fields DiagnosisCode, DiagnosisDesc
I have a another table called dbo_OP_APPOINTMENT_PROCEDURE_PIVOT
With fields Procedure01, Procedure02, Procedure03, Procedure04, Procedure05, Procedure06, Procedure07, Procedure08, Procedure09, Procedure10, Procedure11, Procedure12.
(for info purposes the relationship here is DiagnosisCode = Procedure01, 02, 03 etc)
Is it possible to right a query that shows all records in dbo_OP_APPOINTMENT_PROCEDURE_PIVOT where the DiagnosisCode in table PneumoniaCareBundleDiagnosisCodes appear in any of the Procedure01, 02, 03 fields etc.
If I was using an IF statement the logic i would right it as follows:
IF dbo_OP_APPOINTMENT_PROCEDURE_PIVOT.Procedure01
IS IN PneumoniaCareBundleDiagnosisCodes.DiagnosisCode OR
IF dbo_OP_APPOINTMENT_PROCEDURE_PIVOT.Procedure02
[Code] ......
View 5 Replies
View Related
Jun 10, 2015
I am writing below query to pull from customer table.
select * from Customer where SrNo in (Select distinct SrNo from Orders)
This is doing an exact match of SrNo in Orders table SrNo is part of string and can occur at any place in that string. I want to use the like command.
Please see below example.
select
*
from Customer
where SrNo
like('%89898989%','%928hhst%')
View 2 Replies
View Related
Sep 22, 2014
I am trying to use SQL to pull unique records from a large table. The table consists of people with in and out dates. Some people have duplicate entries with the same IN and OUT dates, others have duplicate IN dates but sometimes are missing an OUT date, and some don’t have an IN date but have an OUT date.
What I need to do is pull a report of all Unique Names with Unique IN and OUT dates (and not pull duplicate IN and OUT dates based on the Name).
I have tried 2 statements:
#1:
SELECT DISTINCT tblTable1.Name, tblTable1.INDate
FROM tblTable1
WHERE (((tblTable1.Priority)="high") AND ((tblTable1.ReportDate)>#12/27/2013#))
GROUP BY tblTable1.Name, tblTable1.INDate
ORDER BY tblTable1.Name;
#2:
SELECT DISTINCT tblTable1.Name, tblTable1.INDate
FROM tblTable1
WHERE (((tblTable1.Priority)="high") AND ((tblTable1.ReportDate)>#12/27/2013#))
UNION SELECT DISTINCT tblTable1.Name, tblTable1.INDate
FROM tblTable1
WHERE (((tblTable1.Priority)="high") AND ((tblTable1.ReportDate)>#12/27/2013#));
Both of these work great… until I the OUT date. Once it starts to pull the outdate, it also pulls all those who have a duplicate IN date but the OUT date is missing.
Example:
NameINOUT
John Smith1/1/20141/2/2014
John Smith1/1/2014(blank)
I am very new to SQL and I am pretty sure I am missing something very simple… Is there a statement that can filter to ensure no duplicates appear on the query?
View 1 Replies
View Related
Mar 16, 2004
I want to pull ALL users from Table1 and include information that person may have in Table2. As of now, it is only including users that have something in Table2. How do I include everyone?
Thanks
View 1 Replies
View Related
Aug 22, 2005
I am new to SQL, as old as it is. I am not new to programming Inormally just use Access.I have two tables for a little project manager I made. After updates Isent an email to the user. I need to populate the user based on the"Assigned To" field I use, but I only log the username and not theemail address. Is there a way to associate the "Assigned To" to theUser's account in the "User" table so that I can pull thier emailaddress through code?ThanksChuck
View 5 Replies
View Related
Jun 19, 2012
I've got a subquery that keeps throwing up an error but I can’t think of another way of completing the query.
Firstly I need to find records where TestQty =3
(this would find 2 records with TestQty =3, TestNumber, 7171003 and 7088650)
The TestNumber is not unique so I would like the final set of records to include all the records with TestNumber, 7171003 and 7088650
TestNumberTestQty
7088650____________3
7088650____________1
7088650____________2
7088650____________1
7088650____________2
7171003____________1
7171003____________3
7171003____________2
Code below:
[Code SQL]
USE TestWarehouse
IF ('dbo.TestItems') IS NOT NULL
DROP TABLE [dbo].[TestItems];
GO
CREATE TABLE [dbo].[TestItems]
( TestItem int not null IDENTITY (1,1)
[Code] .....
View 5 Replies
View Related
May 4, 2006
Hi everybody,
I like to display the records for AccountNo = 221 from table records shown below, how would I do this? I am display this results in a crystal report. What is sql statement to do this? Thanks.
Sql Statement: (this statement is not allowed)
Select AccountNo, RecordID, (Select Description From Table1 Where RecordID In (Select RecordID From Table2 Where Date < '04/05/2006')) As Description, Amount From Table2 Where Date < '04/05/2006'
Desired Result:
AccountNo RecordID Description Amount
221 20 Whew 290.00
221 21 Hi There Good Morning 728.00
Table 1
RecordID Description
20 Whew
21 Hi
21 There
21 Good Morning
Table 2
Date AccountNo RecordID Amount
04/02/2006 220 19 80.0
04/03/2006 221 20 290.0
04/04/2006 221 21 728.0
04/06/2006 223 23 200.3
04/07/2006 225 25 2893.20
den2005
View 3 Replies
View Related