Need Some Assistance With A Group By Case

Oct 11, 2006

Code:


Select Signal_id, Test =
CASE
WHEN signal_date > dateadd(hour,-24,getdate()) THEN 'Today'
WHEN signal_date > dateadd(hour,-48,getdate()) and signal_date < dateadd(hour,-24,getdate()) THEN 'Today-1'
WHEN signal_date > dateadd(hour,-72,getdate()) and signal_date < dateadd(hour,-48,getdate()) THEN 'Today-2'
WHEN signal_date > dateadd(hour,-96,getdate()) and signal_date < dateadd(hour,-72,getdate()) THEN 'Today-3'
WHEN signal_date > dateadd(hour,-120,getdate()) and signal_date < dateadd(hour,-96,getdate()) THEN 'Today-4'
WHEN signal_date > dateadd(hour,-144,getdate()) and signal_date < dateadd(hour,-120,getdate()) THEN 'Today-5'
WHEN signal_date > dateadd(hour,-168,getdate()) and signal_date < dateadd(hour,-144,getdate()) THEN 'Today-6'
WHEN signal_date > dateadd(hour,-192,getdate()) and signal_date < dateadd(hour,-168,getdate()) THEN 'Today-7'
WHEN signal_date > dateadd(hour,-216,getdate()) and signal_date < dateadd(hour,-192,getdate()) THEN 'Today-8'
WHEN signal_date > dateadd(hour,-240,getdate()) and signal_date < dateadd(hour,-216,getdate()) THEN 'Today-9'
ELSE 'Other'
END
, Total = count(*)
From abmsignal WHERE Signal_id = 'fail test' AND Signal_date > dateadd(hour,-240,getdate())
Group by Signal_id, Test
COMPUTE AVG(SUM(Total))




That's what I would like, Daily (or rather 24 hour periods) listed, and then averaged out. I will fix the dateadds so that they are for previous 10 days rather than previous 240 hours, but first I need to get it to work as is.

View 2 Replies


ADVERTISEMENT

Group With A Case?

Mar 26, 2002

I have a SQL statement below which has a case clause which works fine, until I want to group it. Is it possible to group on a clause that is defined as case?

declare @sdate datetime
set @sdate = '02/01/2002'
select distinct count(tbm.otheridnumber), instatus
= case inmate_status
when 'inactive' then 'Out of system'
else 'Active'
end,inm.df_institutionname
from tb_medication tbm
inner join inmateid inm
on tbm.inmate_cntr_id = inm.inmate_cntr_id
where
tbm.chdpedt is null
and DATEDIFF(day,chdpstdt , @sdate) > 90
group by instatus,
inm.df_institutionname
order by inm.df_institutionname

View 1 Replies View Related

Question Regarding CASE And GROUP BY

Jan 21, 2004

I have the below query and I am not sure if this will return an accurate aggregate, I know I cannot just group by my alias GLG_DELEGATE_ID, is this the way to handle aggregates when you have a CASE in the SELECT statement?

SELECT CASE
WHEN C.GLG_DELEGATE_ID IS null THEN C.GLG_ID
ELSE C.GLG_DELEGATE_ID
END AS GLG_DELEGATE_ID
,COUNT(P.CONSULTATION_ID) ACTIVITY_AMOUNT
FROM
dbo.CONSULTATION C
GROUP BY
C.GLG_DELEGATE_ID
, C.GLG_ID

View 1 Replies View Related

Group By Case Statement

May 13, 2007

Hi guys,
I am having a little diffulty displaying two columns next to each other in a case/group by statement as code shown below.
I was wondering if i could have the results displayed such that the gst_amount and total_amount are in two separate columns (as they currently are) however the results of the rows are in the same row not in separate rows (as they are currently). I dont think i can do this in the current case statement that i have (i.e: the two case statements).
Any feedback would be appreciated


SELECT distinct
PERIOD.STARTDATE,
temp_111.EVENTTYPEID,
case when temp_111.[name] like '%GST%'
then sum(temp_111.CONTRIBUTIONVALUE)
end as GST_AMOUNT,
case when temp_111.[name] not like '%GST%'
then sum(temp_111.CONTRIBUTIONVALUE)
end as Total_Amount
FROM temp_111 INNER JOIN PERIOD
ON temp_111.PERIODSEQ = PERIOD.PERIODSEQ
WHERE
(NOT temp_111.PRODUCTID = 'IIIE' OR temp_111.PRODUCTID IS NULL)
AND temp_111.PERIODSEQ in ('111')
group by PERIOD.STARTDATE,
temp_111.EVENTTYPEID,
temp_111.[name]


Here is the current result displayed:


Startdate eventtypeid gst_amount Total_amount
2006-11-01 00:00:00.000NelNULL 83470.5608000000
2006-11-01 00:00:00.000NelNULL 161408.5264874810
2006-11-01 00:00:00.000NelNULL 677568.2683000000
2006-11-01 00:00:00.000NelNULL 2645478.1215092400
2006-11-01 00:00:00.000Nel8347.0560800000 NULL
2006-11-01 00:00:00.000Nel16140.8526488160NULL
2006-11-01 00:00:00.000Nel67756.8268300000NULL
2006-11-01 00:00:00.000Nel264547.8121507070NULL



Instead I want the result to show something like this:


Startdate eventtypeid gst_amount Total_amount
2006-11-01 00:00:00.000Nel8347.0560800000 83470.5608000000
2006-11-01 00:00:00.000Nel16140.8526488160 161408.5264874810
2006-11-01 00:00:00.000Nel67756.8268300000 677568.2683000000
2006-11-01 00:00:00.000Nel264547.8121507070 2645478.1215092400

View 2 Replies View Related

USING 'CASE' TO GROUP DATA

Aug 22, 2006

Hi,Can anyone please help me with SQL syntax to create a second variablebased on the value of another (both numeric)?My effort is below but I get a syntax error.SELECTcharA,CASE charAWHEN < -199 THEN 2WHEN < 31 THEN 3WHEN < 82 THEN 4WHEN < 100 THEN 5WHEN < 105 THEN 6WHEN < 111 THEN 7WHEN < 143 THEN 8WHEN < 165 THEN 9WHEN < 233 THEN 10WHEN >= 233 THEN 11END AS Bin_charAFROM XServer: Msg 170, Level 15, State 1, Line 6Line 6: Incorrect syntax near '<'.

View 3 Replies View Related

Group Case Sensitive

Jul 25, 2006

It appears that table grouping is case sensitive (for example, Re-Roof versus Re-roof appears to be causing a group break). I can't find a parameter to change this behaviour in Reporting Services.
Can anyone verify that it is in fact case sensitive? How to change?

I am running SQL Server 2000 and the database that I am querying is not case sensitive.

View 9 Replies View Related

GROUP BY, CASE (easy) Problem

Nov 16, 2006

I am not to experienced with SQL and I guess the following is a piece of cake for most of you...
I want to get the sales amount for each shop, for each of three different products, and for the sum of the three products. The problem is that I only get for each shop for each of the product, but not the sum of the three products OR for each shop the total of the three products, but not for each product.

My query looks like this:

SELECT

Shop_name,

case

when prod in (1,2,3) then ‘milk_bread_butter’

when prod = 1 then ‘milk’

when prod = 2 then ‘bread’

when prod=3 then ‘butter’

else ‘none’

end as product,

sum(sales_amount) as sales

FROM

Dbo.sales

GROUP BY

Shop_name,

case

when prod in (1,2,3) then ‘milk_bread_butter’

when prod = 1 then ‘milk’

when prod = 2 then ‘bread’

when prod=3 then ‘butter’

else ‘none’

end



The problem is that I only get the lin 'milk_bread_butter' per shop. If I switch the order around in the case statement;

case

when prod = 1 then ‘milk’

when prod = 2 then ‘bread’

when prod=3 then ‘butter’

when prod in (1,2,3) then ‘milk_bread_butter’

else ‘none’



I get the sales amounts per shop for each of the products, but not for the milk_bread_butter total.



I would be very greatful for any guidance as how to solve this.

Thank you.

Best, Mal

View 3 Replies View Related

Transact-SQL Help - CASE Statement And Group By

Jul 20, 2005

I've always been mistified why you can't use a column alias in the group byclause (i.e. you have to re-iterate the entire expression in the group byclause after having already done it once in the select statement). I'mmostly a SQL hobbiest, so it's possible that I am not doing this in the mostefficient manner. Anyone care to comment on this with relation to thefollowing example (is there a way to acheive this without re-stating theentire CASE statement again in the Group By clause?):Select 'Age' =CaseWHEN(SubmittedOn >= DATEADD(dd, - 30, GETDATE())) AND (SubmittedOn <=DATEADD(dd, - 0, GETDATE()))THEN '0-30 Days Old'WHEN(SubmittedOn >= DATEADD(dd, - 60, GETDATE())) AND (SubmittedOn <=DATEADD(dd, - 31, GETDATE())) Then '31-60 Days Old'WHEN(SubmittedOn >= DATEADD(dd, - 90, GETDATE())) AND (SubmittedOn <=DATEADD(dd, - 61, GETDATE())) Then '61-90 Days Old'WHEN(SubmittedOn <= DATEADD(dd, - 91, GETDATE())) THEN '91+ Days Old'ELSE cast(SubmittedOn as varchar(22))end,max(SubmittedOn), COUNT(SCRID) AS NbrSCRsFrom SCRViewWHERE(StatusSort < 90) ANDCustomerID = 8 andUserID = 133group byCaseWHEN(SubmittedOn >= DATEADD(dd, - 30, GETDATE())) AND (SubmittedOn <=DATEADD(dd, - 0, GETDATE()))THEN '0-30 Days Old'WHEN(SubmittedOn >= DATEADD(dd, - 60, GETDATE())) AND (SubmittedOn <=DATEADD(dd, - 31, GETDATE())) Then '31-60 Days Old'WHEN(SubmittedOn >= DATEADD(dd, - 90, GETDATE())) AND (SubmittedOn <=DATEADD(dd, - 61, GETDATE())) Then '61-90 Days Old'WHEN(SubmittedOn <= DATEADD(dd, - 91, GETDATE())) THEN '91+ Days Old'ELSE cast(SubmittedOn as varchar(22))endOrder by max(submittedon) descThanks,Chad

View 4 Replies View Related

Using A Field Alias For A CASE Statement In A GROUP BY Clause

May 20, 2004

When I created a CASE statement (This is at work, Pat:)) it is about 30-40 lines long. I gave it a name and set the name = to the case statement:

ie,

SELECT fieldname1 =
CASE
WHEN condition THEN 'blah blah'
WHEN condition THEN 'blah blah'
WHEN condition THEN 'blah blah'
ELSE thisandthat
END
, fieldname2
, fieldname3
FROM tablename1
GROUP BY CASE
WHEN condition THEN 'blah blah'
WHEN condition THEN 'blah blah'
WHEN condition THEN 'blah blah'
ELSE thisandthat
END, , fieldname2, fieldname3

etc.


The long CASE statement in my GROUP BY is awkward to me. Is this the only way to do it? I tried using the fieldname1 but it comes back as an invalid field name and asks for the "expression".

Regards,

Dave

View 5 Replies View Related

Problem With Group By When Using Case Statements In The Select List.

Oct 11, 2007



I am using SQL Server 2005 and fairly new at using SQL Server. I am having problems using a Case statements in the select list while have a group by line. The SQL will parse successfully but when I try to execute the statement I get the following error twice :

Column 'dbo.REDEMPTIONHISTORY.QUANTITY' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.



Below is the my sql statement:

SELECT dbo.DateOnly(TH.TransactionDate) AS RptDate, RH.Item,

ItemRef =

Case

when RH.Quantity < 0 then Sum(RH.Quantity)

when RH.Quantity >= 0 then Sum(0)

end

FROM dbo.RHISTORY AS RH INNER JOIN
dbo.TRANSHISTORY AS TH ON RH.TRANSACTIONID = TH.TransactionID

WHERE (dbo.DateOnly(TH.TransactionDate) BETWEEN '10-1-2007' AND '10-5-2007')
AND (RH.TransactionCode IN (13, 14, 15, 16))

Group by dbo.DateOnly(TH.TransactionDate), RH.Item

The TransHistory table contains, primary key transactionid, TransactionDate and the RHistory contains all the details about the transaction, the RHistory table is joined to the TransHistory table by foreign key TransactionID. I am trying to get totals for same item on the same day.

Any help will be greatly appreciated. I am also having trouble using If..Then statements in a select list and can not fin the correct syntax to use for that.

View 12 Replies View Related

Transact SQL :: Adding Case When Statement With Group By Query Doesn't Aggregate Records

Aug 28, 2015

I have a a Group By query which is working fine aggregating records by city.  Now I have a requirement to focus on one city and then group the other cities to 'Other'.  Here is the query which works:

Select [City]= CASE WHEN [City] = 'St. Louis' THEN 'St. Louis' ELSE 'Other Missouri City' END, SUM([Cars]) AS 'Total Cars' 
From [Output-MarketAnalysis]
Where [City] IN ('St. Louis','Kansas City','Columbia', 'Jefferson City','Joplin') AND [Status] = 'Active'
Group by [City]

Here is the result:

St. Louis 1000
Kansas City 800
Columbia 700
Jefferson City 650
Joplin 300

When I add this Case When statement to roll up the city information it changes the name of the city to 'Other Missouri City' however it does not aggregate all Cities with the value 'Other Missouri City':

Select [City]= CASE WHEN [City] = 'St. Louis' THEN 'St. Louis' ELSE 'Other Missouri City' END, SUM([Cars]) AS 'Total Cars' 
From [Output-MarketAnalysis]
Where [City] IN ('St. Louis','Kansas City','Columbia', 'Jefferson City','Joplin') AND [Status] = 'Active'
Group by [City]

Here is the result:

St. Louis 1000
Other Missouri City 800
Other Missouri City 700
Other Missouri City 650
Other Missouri City 300

What I would like to see is a result like:

St. Louis 1000
Other Missouri City 2450

View 5 Replies View Related

Reporting Services :: Display Group Name Value Of Each Group In Column Header Outside The Group?

Sep 29, 2015

I have an SSRS 2012 table report with groups; each group is broken ie. one group for one page, and there are multiple groups in multiple pages.

'GroupName' column has multiple values - X,Y,Z,......

I need to group 'GroupName' with X,Y,Z,..... ie value X in page 1,value Y in page 2, value Z in page 3...

Now, I need to display another column (ABC) in this table report (outside the group column 'GroupName'); this outside column itself is another column header (not a group header) in the table (report) and it derives its name partly from the 'GroupName'  values:

Example:

Value X for GroupName in page 1 will mean, in page 1, column Name of ABC column must be ABC-X Value Y for GroupName in page 2 will mean, in page 2, column Name of ABC column must be ABC-Y Value Z for GroupName in page 3 will mean, in page 3, column Name of
ABC column must be ABC-Z

ie the column name of ABC (Clm ABC)  must be dynamic as per the GroupName values (X,Y,Z....)

Page1:

GroupName                 Clm ABC-X

X

Page2:

GroupName                 Clm ABC-Y

Y

Page3:

GroupName                 Clm ABC-Z

Z

I have been able to use First(ReportItems!GroupName.Value) in the Page Header to get GroupNames displayed in each page; I get X in page 1, Y in page 2, Z in page 3.....

However, when I use ReportItems (that refers to a group name) in the Report Body outside the group,

I get the following error:

Report item expressions can only refer to other report items within the same grouping scope or a containing grouping scope

I need to get the X, Y, Z ... in each page for the column ABC.

I have been able to use this - First(Fields!GroupName.Value); however, I get ABC-X, ABC-X, ABC-X in each of the pages for the ABC column, instead of ABC-X in page 1, ABC-Y in page 2, ABC-Z in page 3, ...

View 4 Replies View Related

SQL / ASP Assistance

Oct 23, 2007

Hi Folks,
 I have a slight problem designing two drop down lists accessing my database as some clients are listed twice because they are located in multiple citys
 I have one table called Clients with the following columns
Client
City
F_name
L_name
ID
I am using SELECT DISTINCT Client FROM  Clients for my first Dropdownlist with a postback etc.
 e.g.
Brown
Black
The Second Dropdownlist must select the different Distinct City Values where they are located on selecting Dropdownlist one
e.g.
Brown > London, New York
or
Black > Singapore and Boston
 What SQL Code can i place so the second dropdownlist will select the correct values on selecting the first Dropdownlist.
 
Thanks,
Sully
 

View 4 Replies View Related

SQL Assistance

Sep 16, 1999

I need some explanantion on the following query that I'm trying to run:

if exists (select * from sysobjects
where id = object_id ('slice_trace')
and sysstat & 0xf = 3)
delete from slice_trace
where control_seq_number = 130
and claim_number = 7912450

When I run this query within a database where the slice_trace table does NOT exist, it still seems to execute the delete statement and hence fails because the object is not there.
Essesntially I need this statement to execute only in databases where the table exists.

View 3 Replies View Related

Need Assistance On Max

Apr 9, 2008

I new it was a mistake changing from mysql to mssql! I'm having difficulty with the following and would really appreciate any help you could offer.

I have two tables.

The first [users] has personal details:
[id]
[business_name]
[title]
[surname]
[firstname]

The second [orders] has their orders:
[order_id]
[user_id]
[order_date]
[order_price]

I need a query that returns the latest record from [orders] for each member, with member details, but only where the latest order was within (now)-425.

Many thanks.

View 1 Replies View Related

Need Assistance With T-SQL

Mar 19, 2008

Dear friends!
I'd like to ask your assistance in writing some T-SQL.
I have a table

MYTABLE (THEDATE datetime, TEMPERATURE numeric(4))

3.02 15
4.02 16
5.02 16
8.02 13
10.02 15
11.02 15
12.02 19

I need a T-SQL without using analitic(range) functions like RANK or DENSE-RANK to provide the following output:

3.02 15
4.02 16
8.02 13
10.02 15
12.02 19

In other words I need to obtain only first occurance of the "neibough" adjacent rows where the temperature is equal.

Please advice.
Thanks in advance.

View 4 Replies View Related

Assistance Please Using Txt

Jul 20, 2005

I have received a table of data that has a field containing dateinformation. Unfortunately it was derived from a MainFrame dump andoriginated as a txt file and was then ported into an Access MDB filebefore it became an SQL table. The date format is vchar(50) andactually is comprised of 6 charecters ie: 010104 for Jan 1 2004. Ineed to run a select statement for a range of dates such as 010104thru 030104. Unfortunately being a charecter field this returnsincorrect results under a majority of cases. Back in my dBase daysthere was a VAL() that could be used in this case but I have beenunable to find anything comperable in SQL. Can anyone help me please?Thanks in advanceSteve

View 2 Replies View Related

I Need Assistance Please

Jul 27, 2007

Error: "A connection was successfully established with the server, but an error occurred during the pre-login handshake. (provider: SSL Provider, error:0 - The certificate chain was issues by an authority that is not trusted.) (Microsoft SQL Server)

I am running SQL Server 2005 Developer ed. Windows XP SP2
Trying to connect over the internet to a SQL Server 2005 Workgroup ed. SP1 on Windows Small Business Server 2003 SP1
I have had success doing this before.
I can terminal sevice in to the box and confirm my credentials work
"Force Enycrption" has not been enabled on either the server or the client
The Certificate tab is clear under "Protocols for MSSQLServer", but the server does have certs I can see them in the "Certificate" dropdown.

Any help would be great.

John

View 11 Replies View Related

T-SQL Assistance

Feb 28, 2008

Hey all,

I have been working for some time on this T-SQL statement and getting it to work the way I would like it to work. I have been reading through books and everything, but am still having trouble. I am pretty new to T-SQL so I am probably making some beginners mistakes.

Basically I am working on a SQL 2005 server and I have a single database with two tables. Below are the tables and the fields that I am using from each. The table name is in bold and the fields are plain.

Users
username (PK, varchar(7), not null)
full_name (varchar(50), not null)

call_history
queue (varchar(6), not null)
update_date (datetime, null)
status (char(1), not null)

Ok, now that you have the gist of the tables and fields. What I am trying to do is the impossible I think. Basically I work in a call center that supports software. The queue field is the identifier of what specialist is handling any call within the table. It can be linked to the "username" on the Users table. One thing I just noticed is that the varchar has a difference. Will that affect my below select statement?

SELECT u.full_name AS 'Specialist Name', COUNT (*)
FROM dbo.call_history c
LEFT OUTER JOIN dbo.users u ON c.queue = u.username
WHERE (c.status = 'P') AND (DATEDIFF(dayofyear, update_date, getdate()) >= 6) AND (DATEDIFF(dayofyear, update_date, getdate()) <= 9)
AND queue IN('alatif', 'AWILLI', 'AYOUNG', 'BPRING', 'CSKINN', 'DALDEN', 'DBACCH', 'DGIZZI', 'DKUSSA', 'DMCCUE',
'EKEPFE', 'GBACKH', 'GJONES', 'HESTAL', 'JBANKS', 'JCRICH', 'JDELGA', 'JFOLCH', 'JGRAVE', 'JHARRI',
'JLI', 'JMYERS', 'JPOPPE', 'JRICHA', 'JRIMME', 'JTHOMP', 'JWELLS', 'KDUKHI', 'KSTANL', 'LCHAMP', 'LGABOR',
'LHARVE', 'LMONTG', 'LSHORT', 'LTOM', 'MBECK', 'MJONES', 'MVANDE', 'NBROWN','NTOMPK', 'PELLIS',
'RATTAR', 'RDODGE', 'TANDRO', 'TBROWN', 'TDAVIS', 'TNDREX', 'TNORRI', 'YSOSA', 'YWILLI')
GROUP BY full_name
ORDER BY full_name

So here is my dilemma:
I am trying to emulate a spreadsheet that was given to me by my boss. This is pretty much going to determine whether or not I can get a job as the Web Developer. So the spread sheet displays the number of calls that have not been updated in X amount of days for all of our reps. I have been trying so many different varieties from nested SELECT statements now to joins. To put it simply enough, do I need to do a query that populates column by column?

Here is what it should look like:
http://i135.photobucket.com/albums/q129/tico1177/CropperCapture1.jpg

As you can see, I have to include everyone even if they have zero. That is where the problem comes in. When I use the above statement, the list shows up but takes away people from the list instead of keeping them and placing a null for the count. I have tried placing a HAVING statement at the bottom of the query to compensate for COUNT(*) = 0, but I get an error. I think because I have a WHERE statement.

I am trying to see if this whole thing can be done with a SQL statement to avoid having loop though in code. I basically want to populate a datagridview with the information that I gather.

Is this possible?

All help is greatly appreciated!

View 26 Replies View Related

SQL Server 2008 :: Change Text Format From Case Sensitive To Case Insensitive?

Aug 31, 2015

How can I change my T-SQL text editor from text sensitive to text insensitive?

View 2 Replies View Related

Case Insensitivity Is On Server Wide: Tables Render Case Sensative...

Jan 6, 2005

Hello:

I have created an SQL server table in the past on a server that was all case sensative. Over time I found out that switching to a server that is not case sensative still caused my data to become case sensative. I read an article that said you should rebuild your master database then re-create your tables. So after rebuilding the master database, a basic restore would not be sufficient? I would have to go and manually re-create every single table again?

Any suggestions?

View 4 Replies View Related

SQL Query Assistance

Jan 14, 2008

I am trying to build a related article display. I have a SQLDataSource that I want to be able to select information (Category) from the table (Articles) based on a querystring (ID). SELECT [Category] FROM [Articles] WHERE ([ArticleID] = @ID) which for an example, lets say ID = 1, and it results as Category = Health.That is easy enough, but how would I then select all columns from the table WHERE Category = Result of first SELECT? SELECT * FROM [Articles] WHERE ([Category] = ??? Result of prior select) Can this be done in 1 select command, or would a store procedure need to be written? I am a little lost, sincr I am using a SQLDataSource, and it will be displayed with a Repeater. Thanks!

View 2 Replies View Related

Need Assistance In Using Xp_sendmail

Feb 5, 2008

I'm using SQL 2000 and would like to send a generated email using this stored procedure:
select Libraryrequest.LoanRequestID, Titles.Title, requestors.fname+ ' ' + requestors.lname as [Name], libraryrequest.requestdate,libraryrequest.shipdate,libraryrequest.duedatefrom libraryrequestjoin requestors on requestors.requestorid=libraryrequest.requestoridjoin Titles on Titles.Titleid = Libraryrequest.titleidwhere duedate < DATEADD(day, DATEDIFF(day, '20010101', CURRENT_TIMESTAMP), '20010101')
I know I need to go to Management, SQL Server Agent, Jobs,  New Job.  Do I put the stored procedure in the descriptions part?  After that I'm lost what do I do.
 
Thanks!
 

View 10 Replies View Related

SQL Syntax Assistance

May 23, 2008

Good Morning,
 
I need to write a query to provide MaxDate of each Exam and still show the ID of that Exam. My table is
ID        Exam                Date
1          FMS                1/1/2006
2          FMS                1/1/2007
3          FMS                1/1/2008*
4          ECS                 1/1/2006
5          ECS                 1/1/2007
6          ECS                 1/1/2008* My attempted query isSELECT ID, Exam, Max(Date) AS MaxOfDateFROM Table1
GROUP BY ID, Exam; 
My query actual results
ID        Exam                Date
1          FMS                1/1/2006
2          FMS                1/1/2007
3          FMS                1/1/2008*
4          ECS                 1/1/2006
5          ECS                 1/1/2007
6          ECS                 1/1/2008* My desired results 
ID        Exam                Date
3          ECS                 1/1/2007
6          ECS                 1/1/2007
 
I would appreciate any help that could be provided.
 
Thanks!

View 17 Replies View Related

Need Query Assistance

Jul 28, 2005

First off, here is my query:SELECT DeviationDist.DEVDN, DeviationDist.DEVDD, DEVDA, DEVCT, DEVST, DEVBG, DEVDV, DEVPS, DEVAT, DEVCN, DEVCF, DEVCP, DEVCEFROM DeviationDistINNER JOIN DeviationContact ON DeviationContact.DEVDN = DeviationDist.DEVDNWHERE DeviationDist.DEVDN = '200270'ORDER BY Deviationdist.DEVDN DESCI'm joining the deviationcontact table to the deviation dist table by DEVDN. This query works fine except when the DeviationContact table doesnt contain any records for the DEVDN that the DeviationDist table does contain. In my app, Deviationdist will always have an record for each DEVDN, but DeviationContact may not. I would like to still get the results back for what records exist in the DeviationDist table, even if DeviationContact has no associated records, but still show them if it does...

View 1 Replies View Related

Join Assistance

Jul 24, 2001

-- Joins are not yet my friend.

-- I want all sites even if they are not in the syslog table.

-- select count(gssites.sname) from gssites
-- where gssites.rectype = 'S' = 67

-- this query returns 13 rows, I want all 67

declare @start int, @end int
set @start = 1
set @end = 0
selectgssites.sname'SyncSite'
,syslog.resultcode'RES'
,rtrim(convert(varchar(2),datepart(month,SYSLOG.ON DATE))
+'-'+convert(varchar(2),datepart(day,SYSLOG.ONDATE ))
+'-'+convert(varchar(4),datepart(year,SYSLOG.ONDATE)) )'SyncDate'

from Syslog
left outer join gssites
on gssites.sname = substring(syslog.siteid,9,8)

wheregssites.rectype = 'S'
AND (SYSLOG.RECTYPE='G')
AND (SYSLOG.ONDATE
Between (GetDate()-@start)
And GetDate()-@end)
AND (SYSLOG.SITEID<>'')
AND (SYSLOG.RESULTCODE='SUC')

ORDER BY SyncSite, syslog.ondate

--TIA

jEfFp...

View 2 Replies View Related

Query Assistance

Nov 30, 2005

Hi,

I have a need to renumber or resequence the line numbers for each unique claim number. For background, one claim number many contain many line numbers. For each claim number, I need the sequence number to begin at 1 and then increment, until a new claim number is reached, at which point the sequence number goes back to 1. Here's an example of what I want the results to look like:


ClaimNumber LineNumber SequenceNumber
abc123 1 1
abc123 2 2
abc123 3 3
def321 5 1
def321 6 2
ghi456 2 1
jkl789 3 1
jkl789 4 2


So...
SELECT ClaimNumber, LineNumber, <Some Logic> AS SequenceNumber FROM MyTable


Is there any way to do this?


Thanks,
Dennis

View 4 Replies View Related

Assistance With Trigger

Mar 2, 2004

Hi,

Hopefully this will be painless for you guys/gals - however due to my lack of skills/knowledge I need some clarification.

I have table_X which I have a trigger on INSERT setup.
This trigger updates Field_2 = '1' and inserts some rows in another table.

Is there some way that I can restrict this trigger to only run when Field_1 = "BLAH"
So essentially I am trying to find out how I can pull information/data from the record that fired the trigger and use this in the trigger? (ie to check if Field_1 = "BLAH" and to use Field_3 to further restrict the underlying triggers' updates and inserts)

Hopefully I have given enough information on this one - if not please let me know any points that I should need to clarify.

Thanks in advance for your help!!!

Cheers

View 6 Replies View Related

Query Assistance

Mar 5, 2007

I realize this query is inherently incorrect, but my issue is mainly syntax. The line, "WHEN a.order_id <> b.order_id THEN" is wrong. I want to ensure that a.order_id is not in the settlement table. So I was thinking something along the lines of "WHEN a.order_id not in (select order_id from settlement)" which I know will cause a slower response time, but I'm willing to deal with it. In any case, that syntax doesn't appear to work.

sum(
CASE
WHEN a.ready_to_pay_flag = 'Y' and a.deduction_type = 'E' and (
CASE
WHEN a.order_id <> b.order_id THEN
a.transaction_date
ELSE
b.delivery_date
END) used_date datediff(d,used_date, ".$cutOffDate.") < 30) THEN
a.amount
END) earn_amount_rtp_curr,

Any help here would be hotness!

Thanks!

View 10 Replies View Related

I'd Like To Ask Your Assistance In Writing Some T-

Mar 19, 2008

Dear friends!
I'd like to ask your assistance in writing some T-SQL.
I have a table

MYTABLE (THEDATE datetime, TEMPERATURE numeric(4))

3.02 15
4.02 16
5.02 16
8.02 13
10.02 15
11.02 15
12.02 19

I need a T-SQL without using analitic(range) functions like RANK or DENSE-RANK to provide the following output:

3.02 15
4.02 16
8.02 13
10.02 15
12.02 19

In other words I need to obtain only first occurance of the "neibough" adjacent rows where the temperature is equal.

Please advice.
Thanks in advance.

View 3 Replies View Related

Trigger Assistance

Jul 23, 2005

I have a trigger that I created to log changes in one table to anothertable but it is horribly inefficient.I am hoping that someone with more experience than I can see a way tomake this trigger more efficient.------------ALTER TRIGGER tContacts_ChangeLogON dbo.ContactsFOR UPDATEASSET NOCOUNT ONDECLARE @tablename varchar(20),@record_id_column varchar(30),@colname varchar(30),@colvalue varchar(8000),@insertstmt varchar(1500),@username varchar(20)SELECT @tablename = 'Contacts'SELECT @record_id_column = 'ContactID'DECLARE columns_cursor CURSOR LOCAL FORSELECT COLUMN_NAMEFROMINFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME = @tablenameAND (POWER(2, (ORDINAL_POSITION-1) % 8) & CONVERT(INT,SUBSTRING(COLUMNS_UPDATED(), (ORDINAL_POSITION-1)/8 + 1, 1))) <> 0SELECT * INTO #del FROM deletedSELECT * INTO #ins FROM insertedSELECT @username = RIGHT(SYSTEM_USER, LEN(SYSTEM_USER) -CHARINDEX('',SYSTEM_USER))OPEN columns_cursorFETCH NEXT FROM columns_cursor INTO @colnameWHILE @@FETCH_STATUS = 0BEGINSELECT @insertstmt = 'INSERT INTO ' + @tablename + '_ChangeLog (recordid, fieldname, changedfrom, changedto, username, datetime ) ' +'SELECT d.' + @record_id_column + ', ''' + @colname + ''', d.' +@colname + ', i.' + @colname + ', ''' + @username + ''', GETDATE()' +'FROM #del d INNER JOIN #ins i ON d.' + @record_id_column + ' = i.' +@record_id_column + ' WHERE (i.' + @colname + ' <> d.' + @colname + ')'+' OR (i.' + @colname + ' IS NOT NULL AND ' + 'd.' + @colname + ' ISNULL) OR (i.' + @colname + ' IS NULL AND ' + 'd.' + @colname + ' IS NOTNULL)'-- INSERT INTO Debug (value) VALUES( @insertstmt )EXEC( @insertstmt )FETCH NEXT FROM columns_cursor INTO @colnameENDCLOSE columns_cursorDEALLOCATE columns_cursor

View 8 Replies View Related

Query Assistance

Mar 8, 2006

I am trying to pull some "notes" from a sql database.....the notes thatare put into the database come via the web and the user is entering itfor a certain task. they are stored in their own table and field andget assigned and incremental ID #.I want to be able to pull up the latest entry to the task, not all ofthe notes just the latest one.. The entry does get a timestamp in thefield so I am thinking I might be able to look at that fieldsomehow.... Right now my query shows all notes / entries for the task.I am an intermediate sql query guy so I hopefully expained enough toget assistance.Let me know if you need to know more.

View 2 Replies View Related

Assistance With SQLAgent

May 9, 2008

All,

I have a SQLAgent job created using isqlw to run the query and output the results to a file on the C drive. However, the job never completes, which is strange since the database is fairly new and when I run the query manually in a isqlw window, it completes and outputs the file in seconds.

Any ideas where I'm failing here?

Thanks in advance,

JB

View 4 Replies View Related







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