Selecting Multiple Column From Sub Query.

Apr 17, 2008



Hi,
I am having two tables Products and Transaction

In products I have ProductID and Description. (10 Records)
In Transaction I have ProductID, Lot, Quantity and ListID . ( 4 Million Records)

When I use the inner join between these tables as below query its taking lot of time to give output.

select ProductID, Desc, Lot, qty from Products inner join Transactions on Products.ProductID = Transactions.ProductID
where ListID = '9090909'

otherwise, if I use the below query its takes very few milli seconds to give output but I am not able to get the description from the product table.
select * from Transactions TR where TR.ListID= '9090909' and TR.ProductID in

(select NDC from Products where Products.ProductID = TR.ProductID)

Any from can help me to get the description too at very few times.

Regards,

View 1 Replies


ADVERTISEMENT

Transact SQL :: Distinct By One Column By Selecting Multiple Column?

Jul 17, 2015

I have a SQL Query issue you can find in SQL Fiddle

SQL FIDDLE for Demo

My query was like this

For Insert
Insert into Employee values('aa', 'T', 'qqq')
Insert into Employee values('aa' , 'F' , 'qqq')
Insert into Employee values('bb', 'F' , 'eee')
Insert into Employee values('cc' , 'T' , 'rrr')
Insert into Employee values('cc' , 'pp' , 'aaa')
Insert into Employee values('cc' , 'Zz' , 'bab')
Insert into Employee values('cc' , 'ZZ' , 'bac')
For select
select col1,MAX(col2) as Col2,Max(Col3) as Col3
from Employee
group by Col1

I supposed to get last row as 

    cc  Zz  bab

Instead I am getting 

  cc  Zz  rrr 

which is wrong

View 8 Replies View Related

Selecting A Column From Multiple Tables

Feb 19, 2004

Hello,

Is it possible to get a list of rows from Multiple tables which have the same Column Name. I have 3 tables which comtain similar info
and I want to get a list of Names
the structure is

ID;Name;Address;Phone No.


I was thinking something along the lines of SELECT Name FROM TABLE1,TABLE2, TABLE3

But this does not work.

Is there a nice way of doing this with SQL or should I do code outside the SQL DB

View 4 Replies View Related

T-SQL (SS2K8) :: Selecting Data From Table With Multiple Conditions On Multiple Columns

Apr 15, 2014

I am facing a problem in writing the stored procedure for multiple search criteria.

I am trying to write the query in the Procedure as follows

Select * from Car
where Price=@Price1 or Price=@price2 or Price=@price=3
and
where Manufacture=@Manufacture1 or Manufacture=@Manufacture2 or Manufacture=@Manufacture3
and
where Model=@Model1 or Model=@Model2 or Model=@Model3
and
where City=@City1 or City=@City2 or City=@City3

I am Not sure of the query but am trying to get the list of cars that are to be filtered based on the user input.

View 4 Replies View Related

Selecting Multiple Records By Multiple Filters...

Aug 13, 2006

Hey all,I am having some serious trouble getting the correct syntax for a select statement to work the way I need it, any help I could get on this would be greatly appreciated.I have a table called Units which stores computers and a table called Software which stores software. I have a bit field in Units called OEM, when this is set to true I don't want the select statement to pull this unit down when I am assigning software to other units.Here is my select statement: SELECT Software.SID, Software.SN, Software.Name, Users.First + ' ' + Users.Last AS 'Assigned User', Units.Make + '-' + Units.Model AS 'Assigned Unit' FROM dbo.Software LEFT JOIN dbo.Units ON Software.SN = Units.SN LEFT JOIN dbo.Users ON Units.UID = Users.UID WHERE (Units.OEM = 'FALSE') AND (Software.SN LIKE '%' + @SearchString + '%')Everything works as expected, unless of course the unit has no software assigned to it yet, it won't return it because its not tied to a Units.OEM field. Is there anyway to have it return ALL records that even arn't joined OR are joined but have OEM set to false?Thanks, let me know if I need to clear anything up.-Matthew

View 2 Replies View Related

Selecting Multiple Records From Multiple Tables

Nov 4, 2004

i want to select all the user tables within the database and then all the records with in each table.
plz tell me one query to do this.

ex: suppose x and y are user tables and x contain 10 records and y contains 20 records . i want a query which displays all 30 records together.

View 1 Replies View Related

Multiple Selects On Same Column, Same Table, One Query

Jul 20, 2005

I want to get a column count several times in one query using differentfilters but can't work out how to do it - can anyone point me in the rightdirection?For example, how would combine these two selects into one query that willlist the total and filtered actions:SELECT COUNT(actions) as actioncount, locationFROM mytableGROUP BY locationSELECT COUNT(actions) as actioncount, locationFROM mytableWHERE mycondition IS NULLGROUP BY location

View 6 Replies View Related

T-SQL (SS2K8) :: How To Show Multiple Values In Column Of Join Query

Nov 6, 2014

in my table i ve the column of item code which contains '1000' ,'2000' ,'3000' series i jus wanna display the output of item codes '1000','2000'series and some of ('3000019','3000020','3000077','3000078').

i tried in my join query

these code left(itemcode,4) in ('1000','2000') or itemcode in ('3000019','3000020','3000077','3000078')

its taking so much of time how t o solve ?

View 1 Replies View Related

HELP With SQL Query: Select Multiple Values From One Column Based On &&<= Condition.

Aug 7, 2007

Hello all. I hope someone can offer me some help. I'm trying to construct a SQL statement that will be run on a Dataset that I have. The trick is that there are many conditions that can apply. I'll describe my situation:

I have about 1700 records in a datatable titled "AISC_Shapes_Table" with 49 columns. What I would like to do is allow the user of my VB application to 'create' a custom query (i.e. advanced search). For now, I'll just discuss two columns; The Section Label titled "AISC_MANUAL_LABEL" and the Weight column "W". The data appears in the following manner:

(AISC_Shapes_Table)

AISC_MANUAL_LABEL W
W44x300 300
W42x200 200
(and so on)
WT22x150 150
WT21x100 100

(and so on)
MT12.5x12.4 12.4
MT12x10 10
(etc.)

I have a listbox which users can select MULTIPLE "Manual Labels" or shapes. They then select a property (W for weight, in this case) and a limitation (greater than a value, less than a value, or between two values). From all this, I create a custom Query string or filter to apply to my BindingSource.Filter method. However I have to use the % wildcard to deal with exceptions. If the user only wants W shapes, I use "...LIKE 'W%'" and "...NOT LIKE 'WT%" to be sure to select ONLY W shapes and no WT's. The problems arises, however, when the user wants multiple shapes in general. If I want to select all the "AISC_MANUAL_LABEL" values with W <= 40, I can't do it. An example of a statement I tried to use to select WT% Labels and MT% labels with weight (W)<=100 is:




Code SnippetSELECT AISC_MANUAL_LABEL, W
FROM AISC_Shape_Table
WHERE (W <= 100) AND ((AISC_MANUAL_LABEL LIKE 'MT%') AND (AISC_MANUAL_LABEL LIKE 'WT%'))



It returns a NULL value to me, which i know is NOT because no such values exist. So, I further investigated and tried to use a subquery seeing if IN, ANY, or ALL would work, but to no avail. Can anyone offer up any suggestions? I know that if I can get an example of ONE of them to work, then I'll easily be able to apply it to all of my cases. Otherwise, am I just going about this the hard way or is it even possible? Please, ANY suggestions will help. Thank you in advance.

Regards,

Steve G.



View 4 Replies View Related

Selecting Min And Max Of Multiple Records?

Sep 27, 2013

What I need is the start and end time of each task, but the issue is there is no unique task number to bind them together.. So for instance the task starts with 'Open-Submitted' and ends with 'Task Approved'. The issue is there can be multiple occurrences in the same file number. I need to be able to split these into multiple tasks with the associated start and stop times.

File IDDatetimesTask Event StatusTask Event NameTask IDEvent ID
File 16/3/13 16:33Open-SubmittedTask is retrievedTSK-12345612345
File 16/3/13 16:44Open-ApprovedTask ApprovedTSK-12345623456
File 16/20/13 18:11Open-SubmittedTask is retrievedTSK-12345634567
File 16/21/13 14:42Open-ApprovedTask ApprovedTSK-12345645678

View 3 Replies View Related

Selecting Multiple Descriptions

Feb 28, 2006

I want to select multiple records based on descriptions that are the same. Descriptions is my column and I really want to find duplicate records based on the description column.

View 2 Replies View Related

Selecting From Multiple Tables

Apr 2, 2007

Hi all.

I'm trying to select from multiple table in one select statement but i'm having problems. Here is the code i'm trying:



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[snow_ors_additionalInfoRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[snow_ors_additionalInfoRead]
GO

CREATE PROCEDURE dbo.snow_ors_additionalInfoRead
@Reference int
AS
SELECT
Account.CanTravel,
Account.SEEmployee,
Account.WorkHours,
Account.DrivingLicence,
Account.CriminalConvictions,
Account.CriminalConvictionsDetails1,
Account.CriminalConvictionsDate1,
Account.CriminalConvictionsDetails2,
Account.CriminalConvictionsDate2,
Account.CriminalConvictionsDetails3,
Account.CriminalConvictionsDate3,
Application.VacancyMonitoring,
Application.VacancyMonitoringDetails
FROM Account, Application
WHERE Account.Reference = @Reference AND
Application.reference = @Reference


GO


Any help at all would be great.

thanks people.

View 5 Replies View Related

Selecting Multiple Columns Into One

Mar 18, 2008

I have a product table that has a productID column and a productName column. Then I have a productCategory table that associates productIDs with categoryIDs. And lastly I have a category table containing a categoryID and categoryName. I want to write a query that will return a table with three columns...productID, productName, and and calculated column containing the categories the product belongs to separated by a comma. A sample output would be...

ProductID____ProductName____Categories
1____________Green Flats____Footwear, Accessories, Women's Apparel
2____________Purple Belt____Accessories, Women's Apparel
3____________Pink Tunic_____Women's Apparel

If any of this isn't clear please feel free to write with questions.
So far I have this query -
SELECT Products.ProductID, ProductName, CategoryName FROM Products, ProductCategory, Categories WHERE Product.ProductID = ProductCategory.ProductID AND Categories.CategoryID = ProductCategory.CategoryID

This returns....
ProductID_____ProductName____CategoryName
1_____________Green Flats____Shoes
1_____________Green Flats____Accessories
1_____________Green Flats____Women's Apparel
2_____________Purple Belt____Accessories
2_____________Purple Belt____Women's Apparel
etc....

Any suggestions on how to remedy this???

View 5 Replies View Related

Selecting Min/Max Over Multiple Rows

Jul 23, 2005

Hello All,I have this table:CREATE TABLE [dbo].[tbl_TESTING] ([ROW_ID] [int] IDENTITY (1, 1) NOT NULL ,[FNAME] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[LASTNAME] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[MOVEDINYR] [int] NULL ,[MOVEDOUTYR] [int] NULL) ON [PRIMARY]GOwith these records:INSERT INTO tbl_TESTINGVALUES('JAMES', 'TAYLOR', '1995', '2000')INSERT INTO tbl_TESTINGVALUES('JAMES', 'TAYLOR', '1994', '2005')What I would like to do is be able to select FIRSTNAME, LASTNAME,MIN(MOVEDINYR), MAX(MOVEDOUTYR) for JAMES TAYLOR e.g.FIRSTNAME=JAMESLASTNAME=TAYLORMOVEDINYR=1994MOVEDOUTYR=2005Some sql syntax help appreciated,thanks in advance!

View 2 Replies View Related

Selecting On Multiple Tables

Aug 13, 2006

Hi there,I'm new to sql and thus I'm having problems with a specific query which Ihope you guys can help me with.Basicly I have a few tables which I'm trying to do a query on:Table groups contains information about specific groups e.g. "Windows" or"Unix".Table users contains information about specific users e.g. "a", "b" or "c".Table users_groups contain information about group relationship (a user canbe in multiple groups) e.g. (a, Windows), (b, Unix), (a, Unix).In this case user c is ungrouped.Now I'd like to find the users which does belong to group Windows and thosewho do not:select distinct username from users_groups where groupname = "Windows" orderby username asc;This works pretty well for finding users in the specific group. In this casethe result is a.However I'd like to get the opposite result (b and c) but I'm stuck.The problem is that I'd like a list of all users excluding those which arein "Windows"Here is a partial query:select distinct users.username from users left join users_groups onusers.username = users_groups.username where users_groups.username is nullorder by users.username asc;This only gives me those users who are not grouped at all. This mean thatuser b is not in those results.Please advise.Thanks in advance.-- Henrik

View 2 Replies View Related

Selecting Multiple Values From One Table

Apr 29, 2008

I have a sql select query that I'm pulling from a "Years" table to link to 3 columns in an Items table.ZCValuesYear table has two colums: YearID and YearYearID        Year1            20042            20053            20064            20075            2008...I want to bind the "Year" value to the three colums in the ZCItem table:     ItemUseFirstYearID     ItemUseLastYearID     ItemYearIDThe query below will pull all the "ID's" for each of the colums, but how would I make it pull the "Year" value (instead of record 4, it would pull 2007 instead)?<asp:SqlDataSource ID="sqlItemSelect" runat="server"         ConnectionString="<%$ ConnectionStrings:MyConnString %>" SelectCommand="SELECT ZCPartVault.PartVaultID, ZCPartVault.PartVaultItemID, ZCValuesYear.Year, ZCItem.ItemName, ZCItem.ItemUseFirstYearID, ZCItem.ItemUseLastYearID         FROM ZCPartVault     FULL OUTER JOIN ZCItem ON ZCPartVault.PartVaultItemID = ZCItem.ItemID     FULL OUTER JOIN ZCValuesYear ON ZCItem.ItemUseLastYearID = ZCValuesYear.YearID AND ZCItem.ItemUseFirstYearID = ZCValuesYear.YearID AND ZCItem.ItemYearID = ZCValuesYear.YearID" >        </asp:SqlDataSource>       

View 2 Replies View Related

T-SQL (SS2K8) :: Selecting Top 1 From Multiple Ranges?

Mar 28, 2014

I have data like the following:

ID COUNTER DATA
1 10 BLAH
1 20 BLAH
2 10 BLAH
3 10 BLAH
2 20 BLAH
2 30 BLAH

What I want to return is:

1 20 BLAH
2 30 BLAH
3 10 BLAH

I want the top 1, having the highest counter from each ID. This is a highly simplified version of that I am pulling which also is between a date range, but same principle.

IE: SELECT * FROM Table WHERE ID in (SELECT DISTINCT ID FROM Table WHERE Date BETWEEN <date> AND <date>

I'd rather keep it in one statement if possible, but if I have to do it in multiple passes then so be it.

View 6 Replies View Related

Selecting Data From Multiple Rows

Jan 22, 2008

Here's my tables:

Students
-----------------------
StudentID | StudentName
-----------------------

StudentClasses
-----------------------
StudentID | ClassName
-----------------------

I'm trying to put data into a gridview in ASP.NET 2.0 like this:

Student | Classes
-----------------
Name1 | ClassName1 ClassName2 ClassName3
Name2 | ClassName1
Name3 | ClassName1 ClassName2

I just need to retrieve names of each class that a student is taking, then print them out one after another.

View 1 Replies View Related

Selecting From Multiple Time Periods

Apr 11, 2008

Your help is greatly appreciated. How do you query each one of the following:

1) SELECT FieldValue WHERE DateTime is from 8:30AM - 12:00PM and 6:00PM - 9:30PM on Mondays thru Fridays (i.e. exclude Sat & Sun) for the whole month of January 2008.

2) SELECT FieldValue WHERE DateTime is from 9:30PM - 8:30AM on Mondays thru Fridays, AND ALL-DAY on Saturdays & Sundays for the whole month of January 2008.

Thank you in advance.

View 8 Replies View Related

Selecting Where Cloumn = Column OR Column = Value

May 29, 2008

Hi
I have a gridview with a sql data source and a few drop down lists where i choose values to sorth what i would like to retrive from the table. The problem im facing is that when i pass values to the database, i can sort out and retrive my items when both my listboxes have selected values.
But when i want to select everything from the table where the column = clumn or cloumn = value i dont get anything back.
I have 2 dropdown lists. One for category and one for location. These are populated drom the database by selecting the column and retriving destinct values. I have a function that fires when one of the dropdown lists are changed witch changes the sql datasource select value so it retrives items sorted by the selected categories and locations.
Here is the function:
    protected void DropDownList_Change(object sender, EventArgs e)    {        string Category = DropDownListKategori.SelectedValue.ToString();        string Location = DropDownListEtabl.SelectedValue.ToString();        SqlDataSource1.SelectCommand = "SELECT ARTNR, ARTTYP, AKTIVITET, DATUM, KUND, PLATS, KOMMENTAR FROM ARTIKEL WHERE ARTTYP = @ARTTYP AND PLATS = @PLATS";        SqlDataSource1.SelectParameters.Clear();        SqlDataSource1.SelectParameters.Add(@"ARTTYP", Category);        SqlDataSource1.SelectParameters.Add(@"PLATS", Location);        SqlDataSource1.DataBind();    }
The dropdown lists have an option to not retrive values by category or location. I have set that value to PLATS and ARTTYP thinking the query would would retrive everything if these were selected
SELECT ARTNR, ARTTYP, AKTIVITET, DATUM, KUND, PLATS, KOMMENTAR FROM ARTIKEL WHERE ARTTYP = ARTTYP AND PLATS = PLATS
however if both these drop down lists are set to not filter, my query gets nothing in return. And if one of the lists has this selected and ther other one has a value, say a location or something nothing is retrived either. However if both columns have something selected i do get values returned.
My speculation is that the query beeing run when this happens is that it is trying to find columns having the value ARTTYP or PLATS (category or location), as a string and actually seeing it as Im trying to retrive values where column = column.
Any suggestions on how i can make my query run as intended or is there another problem Im not seeing.
 

View 7 Replies View Related

How To Select Column Without Selecting A Column Name

Feb 17, 2004

I want to know how to select a Column without selecting a column name

View 6 Replies View Related

T-SQL (SS2K8) :: Selecting Distinct From Multiple Tables

Jun 4, 2014

I have 3 tables:

News:

bigint NewId
nvarchar NewTitle
datetime NewDate
nvarchar NewBrief
--------------------------
Category:

int CatId
nvarchar CatName
--------------------------
NewsRelCategory:

bigint Id
int CategoryIdFk
bigint NewsIdFk
--------------------------

I want to select NewId, NewDate and Distinct NewTitle

I tried this but NewTitle doesn't distinct:

SELECT
FROM dbo.Category INNER JOIN
NewsRelCategory ON dbo.Category.CatId = NewsRelCategory.NrcCategoryIdFk INNER JOIN
dbo.News ON NewsRelCategory.NrcNewsIdFk = dbo.News.NewId

View 9 Replies View Related

Selecting Only 1 Record Based On Multiple Criteria

Jan 31, 2014

I have inherited a query which currently returns multiple instances of each work order because of the joined tables. The code is here and I've detailed the criteria needed below but need the best way to accomplish this:

Select h.worknumber, h.itemcode, h.descr, h.task_descr, h.qty, h.itemised,
h.serialnum, h.manufacturer, h.model_id, h.depot, h.date_in, h.date_approved,
h.est_complete_date, h.actual_complete_date, h.meterstart, h.meterstop,
h.custnum, h.name cust_name, h.addr1, h.addr2, h.town, h.county, h.postcode,
h.country_id, h.contact, h.sitename, h.siteaddr1, h.siteaddr2, h.sitetown,

[Code] ....

Each work order should only be returned once, and with the following additional criteria:

1. i.meter - this should return only the lowest number from that file.

2. sm.next_calendar_date - this should return only the most recent date out of those selected for the certificates on this piece of equipment

3. wh.meterstop as [Last Service Hours],
wh.date_created as [Last Service] - this should return the number from wh.meterstop at the most recent wh.date_created for that piece of equipment.

View 1 Replies View Related

Selecting From Multiple Tables Avoiding Duplicates

Sep 6, 2006

Hi

I currently have two tables called Book and JournalPaper, both of which have a column called Publisher. Currently the data in the Publisher column is the Publisher name that is entered straight into either table and has been duplicated in many cases. To tidy this up I have created a new table called Publisher where each entry will have a unique ID.

I now want to remove the Publisher columns from Book and JournalPaper, replace it with an ID foreign key column and move the Publisher name data into the Publisher table. Is there a way I can do this without duplicating the data as some publishers appear several times on both tables?

Any help with this will be greatly appreciated as my limited SQL is not up to this particular challenge!!!
Thanks!

View 7 Replies View Related

Selecting Records Where Multiple Foreign Keys Are A Certain Value

Jul 23, 2005

Hi All,I'm trying to solve this for a few days now and I just can't figure itout...I have three tables set up, I'll simplify them for this question:Table 1: HOTELSColumns: HOTEL_ID, HOTEL_NAMEExmple row: 123 || 'Hotel X'Table 2: SERVICESColumns: SERVICE_ID, SERVICE_NAMEExample rows:1 || 'Breakfast in bed'2 || 'King size bed'Table 3: LINK_HOTELS_SERVICESColumns: FK_HOTEL_ID, FK_SERVICE_ID, SERVICE_VALUEExample rows:123 || 1 || 1123 || 2 || 1In table 3 I link different services to different hotels. In the same tableI set the "value" for the service.The first example row of table 3 means something like: Hotel X offersBreakfast in bed. In this case 1 stands for TRUEThe second example row of table 3 means: Hotel X offers King size beds(again: 1 stands for TRUE).What I'm struggling with is selecting the hotel ID's which offer multipleservices. To stay in the example: how can I select all hotels whereSERVICE_ID = 1 AND SERVICE_ID = 1. I can't seem to figure out how to doit...I hope anyone can help... Thanks a lot in advance!!!Robert

View 2 Replies View Related

Database Design Selecting Multiple Different Child Tables

Sep 19, 2000

I want to have a linking table say for example we call this a claim. Based on the claim number you need to relate to one of say 6 different types of claims. The types of claims related to their own individual parent table. (individual because each type of claim tracks completely different information) does anyone have an idea on how to set this up?

Sample Structure

table = Claim
Field 1 = ClaimTypeA_ID
Field 2 = ClaimTypeB_ID
Field 3 = ClaimTypeC_ID
Field 4 = ClaimTypeD_ID
Field 5 = ClaimTypeE_ID
Field 6 = ClaimTypeF_ID

The six field relate to the 6 different tables ID.

If I do this how do I store the data? put 0's in each of the claim types that are not used???

Any suggestions would be appreciated.

View 2 Replies View Related

Selecting Unmatched Records Based On Multiple Fields

Jul 21, 2004

I need to list all the records in Table2 which don't have matching field values in Table1.

This the the exact opposite of what I need:
SELECT DISTINCT
Field1,
Field2,
Field3,
Field4,
Field5
FROM
[Table1]
WHERE EXISTS(
SELECT DISTINCT
FieldA,
FieldB,
FieldC,
FieldD,
FieldE
FROM
[Table2]
)

The above seems to give me all records in Table1 in which the five fields match the five fields specified in Table2. What does not show up is the test record I put in Table2 which is not in Table1.

What I need, however, is the exact opposite.

I tried the above using NOT EXISTS but I get no records at all.

How do do this?

View 6 Replies View Related

SQL Server 2012 :: Selecting Records From Multiple Tables?

Jul 1, 2015

i have this query in a proc

declare @bu_id INT,
@CurCaptureDate DATETIME,
@user_id INT,
@col_name VARCHAR(100),
@sort_order VARCHAR(4),
@CityPair_ID INT=NULL,

[code]....

where @reasons and @departure_code can be multiple.

View 2 Replies View Related

Reporting Services :: Multiple Select Parameter Only Selecting First Value?

Sep 8, 2015

I have a SSRS report with a Parameter that lets you choose the name of an employee. The report lists their Name, Number, User ID etc.

When you select a single employee, the filter on the Dataset works perfectly. However once you select two or more employee names, it only returns the first result. 

The parameter, Field, and Filter are text. 

The Filter is EmployeeName IN @EmployeeName

View 8 Replies View Related

Sorting Problem? Most Recent Entry When Selecting Multiple Columns

Oct 19, 2007

I'm trying to determine the oldest timestamp that meets given criteria which includes a specific action_type code. That code can legitimately be performed more than once on an item (all actions are recorded in an actions table, so the full history is available).

actions table (columns: action_id, request_id, action_type, action_time, action_reason)

I'm having trouble getting the most recent timestamp for the given action_type I'm looking for, when that action_type has been performed more than once.

My intent with the query below is to get the most recent action_time and it's request_id that meets the criteria


SELECT TOP 1 a.action_time, r.request_id FROM requests r JOIN incident i ON r.request_id = i.request_id LEFT JOIN actions a ON r.request_id = a.request_id WHERE i.refund_type = 1 AND (r.status_code = 3 OR r.status_code = 14) AND a.action_type = 3 ORDER BY a.action_time


So for example, if the item with request_id 1334 has had action_type 3 performed on it twice, once at 2007-10-15 13:30:00 and then again at 2007-10-17 14:40:00, it's picking up the former, when I want the later. That it had action_type 3 performed on it twice is legitimate. (larger context an item was approved by a manager, then rejected by a processor, and then approved by a manager again after resubmission)

Hopefully this has made sense so far.

So, how do I make sure I'm getting the most recent action time, when I don't know if the item in particular will have more than one of this action type performed on it?

View 5 Replies View Related

Selecting Only Rows That Same The Value In One Column

Jun 5, 2006

Mike writes "Hi,
I am a beginner with TSQL and I hope this is not a silly question :-)

Lets say I have a table with 2 columns, 1 a primary key identity field with increment 1 and the other a char.

EG:

ID ANIMAL
---------
1 CAT
2 DOG
3 PIG
4 RAT
5 PIG
6 DOG
7 DOG
.
.
And so on with many entries

How do I return a selection of rows that have the contents of the ANIMAL field matching 1 or more times

EG:
From above table I want to return rows 2,6 & 7 and 3 & 5 ONLY and not 1(CAT) and 4(RAT) because they only occur once.

In my real life situation I have unknown numeric data in field 2 but the principal is the same.

How do I do this?

Thanks in Advance
Mike"

View 2 Replies View Related

Selecting The Same Column Twice In The Same Where Clause

Jul 23, 2005

Hi :From a crystal report i get a list of employee firstnames as a stringinto my store procedure. Why is it comming this way ? hmmmmmm it's aquestion for me too.ex: "e1,e2,e3"here are my tablestblProjectsProjectId123tblEmployeeemployeeId FirstName1 e12 e23 e3tblProjectsToEmployeeProjectId employeeId1 11 21 32 12 23 13 23 34 14 3i need to find out the project ids all 3 of these employees worked on.so the out put i need isprojectId13How can i get it ????????????now i can use replace command to format it to a OR clause or ANDclauseSET @string= 'employeeId =' + '''' + REPLACE('e1,e2,e3',',',''' ORemployeeId = ''') + ''''some thing like this.OR clause will give me all 4 projects.in('e1','e2','e3') will give me all 4 projects.of cause AND command will not give me any.other method i tried was adding the employee table 3 times into thesame SQL string and doing some thing likeWHERE (empTable1.Firstname ='e1' AND (empTable1.Firstnamein('e2','e3'))AND (empTable2.Firstname ='e2' AND (empTable1.Firstname in('e1','e3'))AND ...and goes alone. this gives me some what i needed. but it's a verymessy way of doing it, because i get a comma seperated stringparameter i have to construct the sql string on the fly.any help or direction on this matter would greatly appreciated.thankseric

View 3 Replies View Related

Selecting The Corresponding Column Value When Using Min Or Max Aggregate.

May 4, 2007

Greetings,

I have a dataset something like this:



Loc Value Time
A 3 1AM
A 8 2AM
A 2 3AM
A 1 4AM
...
B 8 1AM
B 1 2AM
...

When we collapse the Loc group I want to show the Max vlaue and the time it
occurred.



A 8 2AM
B 8 1AM



What is the expression for the Time column of the table to ensure
the time of the maximum value is shown?

Thanks

View 8 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved