Problem With Group By When Using Case Statements In The Select List.
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 Complete Forum Thread with Replies
Related Forum Messages:
Using SQL Query Columns In Select Case Statements
I am using Visual Web Developer Express 2005 as a test environment. I have it connected to a SQL 2000 server. I would like to use a Select Case Statement with the name of a column from a SQL Query as the Case Trigger. Assuming the SQLDataSource is named tCOTSSoftware and the column I want to use is Type, it would look like the following in classic ASP: Select Case tCOTSSoftware("Type") Case 1 execute an SQL Update Command Case 2 execute a different SQL Update Command End Select What would a comparable ASP.Net (Visual Basic) statement look like? How would I access the column name used in the SQLDataSource?
View Replies !
Select Declared Variable With Case Statements
I am trying to gather counts for table imports made for files from friday - sunday and create a variable that will be the body of an email. I'd like to use either a case statement or a while statement since the query is the same but the values must be collected for each day (friday, saturday and sunday) and will all be included in the same email. I have declared all variables appropriately but I will leave that section of the code out. Select @ifiledate = iFileDate from tblTelemark where iFileDate = CASE WHEN iFileDate = REPLACE(CONVERT(VARCHAR(10), GETDATE()-3, 101), '/','') THEN Select @countfri1 = Count(*) from tbl1 Select @countfri2 = Count(*) from tbl2 Select @countfri3 = Count(*) from tbl3 Select @countfri4 = Count(*) from tbl4 WHEN iFileDate = REPLACE(CONVERT(VARCHAR(10), GETDATE()-2, 101), '/','') THEN Select @countsat1 = Count(*) from tbl1 Select @countsat2 = Count(*) from tbl2 Select @countsat3 = Count(*) from tbl3 Select @countsat4 = Count(*) from tbl4 WHEN iFileDate = REPLACE(CONVERT(VARCHAR(10), GETDATE()-1, 101), '/','') THEN Select @countsun1 = Count(*) from tbl1 Select @countsun2 = Count(*) from tbl2 Select @countsun3 = Count(*) from tbl3 Select @countsun4 = Count(*) from tbl4 END Is there a way to do what this that works???
View Replies !
Trying To Use The Results Of A Case Statement In My Select List In My WHERE Clause?
I am fairly new with SQL and still learning. I have used a case statemtent for a column in my select list and want to use the results of that statement's field in my WHERE clause but it is not working for me. Here is the code I have so far: SELECT l.loanid, p.investorid, l.duedate, case when pc.duedate >= l.duedate then pc.duedate end as RateDueDate, pc.interestrate FROM loan l inner join participation p on p.loanid = l.loanid inner join paymentchange pc on pc.loanid = l.loanid where p.investorid = '12345' and RateDueDate is not null order by l.loanid, pc.duedate I want to put the results of this case statment in my where clause like highlighted above but it is not working because RateDueDate is not an actual column in the table. Any help would be greatly appreciated. Thanks!
View Replies !
SELECT With GROUP BY And Build A List From Vales Not Shown
Hard to write a subject line to describe this one. Anayway, I have a table with names and address plus an extra field noting a part number of product. I'd like to build a SELECT string that will return one result for each name/address (uniques only in other words) and build a comma delimited field of all the part numbers for that name/address. Example: NAME ADDRESS PART NUMBER John Smith 555 Main st., los angeles, ca 90003 5000 John Smith 555 Main st., los angeles, ca 90003 6650 Mike Jones 8569 West 18th Ave., San Diego, ca 1255 John Smith 555 Main st., los angeles, ca 90003 5144 Mike Jones 8569 West 18th Ave., San Diego, ca 2399 So I'd like my results to look like this: NAME ADDRESS PARTS John Smith 555 Main st., los angeles, ca 90003 5000,6650,5144 Mike Jones 8569 West 18th Ave., San Diego, ca 1255,2399 THanks in advance for any suggestions! Raul
View Replies !
Iif And Case Statements
Hi all,I have to translate an Access query into sql. The query has thefollowing statement. I know SQL doesn't support iif, so can someone tellme how to use the case statement to get the same result?select field1,IIf(Grand_total-50>0, grand_total-50, 0) AS field2,field3Thanks.*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View Replies !
Using SQL Case Statements HOW???
I'm trying to make a view that uses organization name from one tableand contact first and last name from another table. In the view Ihave a field that I want to show Organization followed by the maincontact. Problem is if the organization field or name field is NULLthen it doesn't show anything. If one field is empty I still want itto show the other field in the table.Example:Org1--ContactOrg2--ContactOrg3 (Still shows org even without a contact name)Contact (Still shows contact even without an org name)Tried using a CASE statement but didn't work.
View Replies !
Case Statements
Hey folks, having a problem here... I have 2 piece of code designed to do the same thing. My problem is, i'm not getting the same results. Code 1 where the results are correct Code: select Count(*) as TotalCount, Sum(DistAmt) as TotalSum from table1 inner join table2 on table2.id = table1.id where MailTypeID = 3 AND MailEventID = 2 and table1.IsActive = 1 code 2 - Y is correct, but Z is not, and not only is it not correct, but it is returning a number which equals more then the total rows from the table. Code: select Y = sum(case when mailtypeid = 3 and maileventid = 2 and IsActive = 1 then distamt else 0 end), Z = count(case when mailtypeid = 3 and maileventid = 2 and IsActive = 1 then 1 else 0 end) from table1 inner join table2 on table2.id = table1.id I have no idea what is going on. Thanks! Caden
View Replies !
Help With CASE And IF Statements
Hi, Is there a way to use more criteria in a CASE statement other than CASE WHEN expression THEN value ELSE value END I need to test if the count is greater than 0. If so, then perform the case statement, else return zeros. Currently there are entries where the values are blank. These blank values are causing errors in the application and unfortunately, I am not able to update these values. So far I have the following, but I am getting an error stating "An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or select list, and the column being aggregated is an outer reference." Thanks in advance! Code: IF @Qid = 4 SELECT @Exp as Status, COUNT(*) AS Total, @CourseID as CourseID, (SELECT question FROM tableQuestions WHERE qid = @Qid) AS Question, IF COUNT(*)>0 THEN 1.0 * SUM(CASE WHEN A.Q1 > 1 THEN 1 ELSE 0 END) / COUNT(*) AS Positive, 1.0 * SUM(CASE WHEN A.Q1 = 0 THEN 1 ELSE 0 END) / COUNT(*) AS Neutral, 1.0 * SUM(CASE WHEN A.Q1 < 0 THEN 1 ELSE 0 END) / COUNT(*) AS Negative, 1.0 * SUM(CASE WHEN A.Q1 = 0 THEN 1 ELSE 0 END) / COUNT(*) AS NA ELSE 0 AS Positive, 0 AS Neutral, 0 AS Negative, 0 AS NA END IF FROM table1 A INNER JOIN table2 B ON A.SessionID = B.SessionID WHERE (B.CourseID = @CourseID) AND (A.SubmitDate >= @BeginDate) AND (A.SubmitDate <=@EndDate)
View Replies !
If Or Case Statements
Does anyone know if there is a way to look at a value in a variable and based on that value run different Data Flow Tasks? For example, let's say I have an SSIS package that contains a variable named Client and 3 separate Data Flow Tasks. I would like to do this: if Client = 1 then run Data Flow 1 else if Client = 2 then run Data Flow 2 else run Data Flow 3. Is this possible? Thanks. Danielle
View Replies !
CASE Statements
Hi is it possible to have a case statement with 2 or more constraints ? Like we have CASE x WHEN 1 THEN .. WHEN 2 THEN .. but what if i want a constraint like : IF (x= 0 AND y=0) { then... } can this be done in a CASE statement ? if not , can I use IF with SQL ?
View Replies !
Use Of Case Statements.
hi, I want to know how can i equate the following case statements into one Condition? Following is my Code (case when ws.Action_Taken_ID not in(3,17,18) then '-1' else '0' end) as istechfcr, (case when datediff(day,dbo.Usp_Get_Date(pr.Set_Serial_Number),oh.WO_Record_Date) <= q.Product_Gurantee_Months + 6 then '-1' else '0' end) as istechfcr, (case when substring(ltrim(rtrim(ws.Symptom)),1,1) not in('X') then '-1' else '0' end) as istechfcr, (case when ws.Action_Taken_ID not in(8,15,21,25) then '-1' else '0' end) as istechfcr, Thanks..
View Replies !
Case Statements
whats the most efficient way to do this? I have a column that contains three values. A, B, C If colVal = A add one to batch a, if B add one to batch b...ect . Then display all three values
View Replies !
Case Statements
I am creating a stored procedure which receives the following 4 variables. However, VacancySectorID is the only madatory variable. @VacancySectorID int = NULL, (mandatory) @VacancyRegionID int = NULL, optional) @VacancyTypeID int = NULL, (optional) @VacancyKeywords nvarchar(64) = NULL, (optional) My objective is to dynamically build the WHERE statement which in turn will return either one or more of the variables and the required data. The following code works for a single if else but it appears that you cannot have more than one if else statement. Anyones input would be greatly appreciated. SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_Public_GetVacancyListingBySearchCriteria] ( @VacancySectorID int = NULL, @VacancyRegionID int = NULL, @VacancyTypeID int = NULL, @VacancyKeywords nvarchar(64) = NULL ) AS --SET NOCOUNT ON; IF @VacancySectorID IS NULL AND @VacancyRegionID Is NULL AND @VacancyTypeID IS NULL AND @VacancyKeywords IS NULL BEGIN SELECTviewVacancies.* FROMviewVacancies WHEREVacancyActive = 1 AND VacancySectorID = @VacancySectorID ORDER BYVacancyPosted DESC, VacancyTitle END ELSE BEGIN SELECTviewVacancies.* FROMviewVacancies WHEREVacancyActive = 1 ORDER BYVacancyPosted DESC, VacancyTitle END
View Replies !
Nested CASE Statements
Hi All, I'am trying to program a nested CASE statements (if this is not possible, does anyone have any alternate suggestions ?) and I'm getting syntax errors. The statement is: SELECT @cmdLine = CASE @BackupType WHEN 1 THEN Select @tmpStr = CASE @initFlag WHEN 1 THEN 'BACKUP Database ' + @databaseName + 'TO '+ @backupDeviceName + ' WITH INIT, NOUNLOAD, NAME = ' + @backupJobName + ' , SKIP , STATS = 10, NOFORMAT' ELSE 'BACKUP Database ' + @databaseName + 'TO '+ @backupDeviceName + ' WITH NOINIT, NOUNLOAD, NAME = ' + @backupJobName + ' , SKIP , STATS = 10, NOFORMAT' END WHEN 2 THEN Select @tmpStr = CASE @initFlag WHEN 1 THEN 'BACKUP Database ' + @databaseName + 'TO '+ @backupDeviceName + ' WITH DIFFERENTIAL, INIT , NOUNLOAD, NAME = ' + @backupJobName + ', SKIP, STATS = 10, NOFORMAT' ELSE 'BACKUP Database ' + @databaseName + 'TO '+ @backupDeviceName + ' WITH DIFFERENTIAL, NOINIT , NOUNLOAD, NAME = ' + @backupJobName + ', SKIP , STATS = 10, NOFORMAT' END WHEN 3 THEN Select @tmpStr = CASE @initFlag WHEN 1 THEN 'BACKUP Log ' + @databaseName + 'TO '+ @backupDeviceName + ' WITH INIT, NOUNLOAD, NAME = ' + @backupJobName + ', SKIP , STATS = 10, NOFORMAT' ELSE 'BACKUP LOG ' + @databaseName + 'TO '+ @backupDeviceName + ' WITH NOINIT, NOUNLOAD, NAME = ' + @backupJobName + ', SKIP , STATS = 10, NOFORMAT' END ELSE '' END TIA, Romy Stevensen
View Replies !
Nesting Case Statements...
I am wondering if there is a way that we could do a nesting case statement in an SQL Query? This is what I have now... FicaWages = CASE WHEN (UPR00900.FICAMWGS_1 + UPR00900.FICAMWGS_2) >= '84900' AND UPR00400.SBJTSSEC = 1 THEN '0' WHEN UPR00400.SBJTSSEC = 0 THEN '0' ELSE (UPR30100.GRWGPRN - (SELECT SUM(UPR30300.UPRTRXAM) FROM UPR30300 WHERE UPR30300.EMPLOYID = UPR00100.EMPLOYID AND UPR30300.PAYROLCD LIKE '3%' AND AUCTRLCD = 'UPRCC00000007')) END What I want: FicaWages = CASE WHEN ('Sql Statement') = 'GRM' THEN CASE WHEN (UPR00900.FICAMWGS_1+UPR00900.FICAMWGS_2) >= '84900' AND UPR00400.SBJTSSEC = 1 THEN '0' WHEN UPR00400.SBJTSSEC = 0 THEN '0' ELSE (UPR30100.GRWGPRN - ('Sql Statement')) END ELSE CASE WHEN (UPR00900.FICAMWGS_1+UPR00900.FICAMWGS_2) >= '84900' AND UPR00400.SBJTSSEC = 1 THEN '0' WHEN UPR00400.SBJTSSEC = 0 THEN '0' ELSE (UPR30100.GRWGPRN - ('Sql Statement')) END END I hope this is clear enough.
View Replies !
Nested Case Statements
Is it possible to use nested case statements in the SQL for your dataset when you are using Reporting Services? I keep getting an error saying "Unable to parse expression" and my report won't run. Code SnippetCASE WHEN (CASE WHEN DateDiff(d , GetDate() , DATEADD(d , - 1 , DATEADD(m , 1 , DATEADD(m , 1 , DATEADD(d , - (1 * (DAY(TRANSACTION_DATE) - 1)) , TRANSACTION_DATE))))) < '0 THEN 'Overdue' WHEN DateDiff(d , GetDate(), DATEADD(m , FIELD1 / 30 - 1 , DATEADD(m , 1 , DATEADD(d , - (1 * (DAY(TRANSACTION_DATE) - 1)) , TRANSACTION_DATE)))) > 0 THEN 'Not Due' ELSE 'Due' END)= 'Not Due' AND FIELD2 > 0 THEN DateDiff(m , GetDate() , DATEADD(m , FIELD1 / 30 - 1 , DATEADD(m , 1 , DATEADD(d , - (1 * (DAY(TRANSACTION_DATE) - 1)) , TRANSACTION_DATE))) * 30) / 360 * FIELD2 * @PARAMETER1 ELSE NULL END I know this is quite a complex statement, so at first I was worried that maybe I had brackets in the wrong places, but I've been through the code and made sure that every opening bracket has an equivalent closing bracket, and everything appears to be OK in that respect. So I'm thinking that maybe the structure of my nested case statements is incorrect? The inner case statement is necessary to calculate whether a transaction is due, overdue or not due. The outer case statement depends on the result of the inner case statement. Basically, we only want the calculations following the "THEN" in the outer case statement to be executed if the result of the inner case statement is "not due" and Field2 is greater than zero. If either of those criteria aren't met, then it should go straight to the ELSE NULL END statement and stop.
View Replies !
Help !!!!!using Case Statements In Update
Hi, I have this update statement that works, it updates the totalamount to calc amount, but I want to update totalamount only when it is not equal to calcamt.I have tried many things but in vain.Can some one please help me. How do i use case statements to update only when totalamount!=calcamt. update c set totalamount= calcamt from Prepay c JOIN ( select sum(amt) as calcamt, payid from pay group by payid )b ON b.payid= c.payid where c.cust_no='somenum'
View Replies !
Nested Case Statements
Hi i am having some trouble with a nested case statement, what i want to do is set the value of a new column called Result depending on a series of case statements. Basically i want to check Test.Webstatus = 'Rd' and FinalResult = 'true' if this is true i want it to set the value in the Results field to ReportableResult + '~' + ReportableUnitDisplay then go through all the limits fields adding either the value of the field or 'blank' onto the end of the value in the Results field, depending on if the limits field has Null or a value in it. Producing a value in the Results field similiar to: 10~kg:10:5:2:1 or 10~kg:blank:5:blank:1 etc select ClientRef, Sample.WebStatus as SampleStatus, Analysis, FinalResult, Test.WebStatus, 'Result' = Case when Test.WebStatus = 'Rd' and FinalResult = 'true' then Case Case when UpperCriticalLimit is null then ReportableResult + '~' + ReportableUnitDisplay + ':blank' else ReportableResult + '~' + ReportableUnitDisplay + ':' + UpperCriticalLimit end Case when UpperWarningLimit is null then ReportableResult + '~' + ReportableUnitDisplay + ':blank' else ReportableResult + '~' + ReportableUnitDisplay + ':' + UpperWarningLimit end Case when LowerWarningLimit is null then ReportableResult + '~' + ReportableUnitDisplay + ':blank' else ReportableResult + '~' + ReportableUnitDisplay + ':' + UpperWarningLimit end Case when LowerCriticalLimit is null then ReportableResult + '~' + ReportableUnitDisplay + ':blank' else ReportableResult + '~' + ReportableUnitDisplay + ':' + LowerCriticalLimit end end when FinalResult = 'false' then Null else Test.WebStatus from Job inner join sample on Job.JobID = Sample.JobID inner join Test on Sample.SampleID = Test.SampleID left join Result on Test.TestID = Result.TestID Any Advice Would Be Great Thanks David
View Replies !
How To Use Case In Update Statements
Hi, I have this update statement that works, it updates the totalamount to calc amount, but I want to update totalamount only when it is not equal to calcamt.I have tried many things but in vain.Can some one please help me. How do i use case statements to update only when totalamount!=calcamt. update c set totalamount= calcamt from Prepay c JOIN (select sum(amt) as calcamt, payid from pay group by payid )b ON b.payid= c.payid where c.cust_no='somenum'
View Replies !
Dividing Two CAse Statements
How do I divide these two case statements: 1. sum(CASE WHEN o.sap_apc_indic is null THEN wip.wip_oth_exp_amt ELSE 0 END) Markup, 2. sum(CASE WHEN o.sap_apc_indic is not null THEN wip.wip_oth_exp_amt ELSE 0 END) AP,
View Replies !
Multiple Case Statements
This query brings back 2 rows for each record, one for each case statement. How can I change this to bring in the contsupp.notes for both types of data? Or could it be fixed in the joins? select contact1.accountno, contact1.key5 as "Ch#", contact2.uexpsort as "Sort", contact1.company as "Church", contact1.contact as "Editor", contact1.phone1 as "Phone", contact2.uemerg as "Emergency", contact1.Address1 as "Address", contact1.city as "City", contact1.state as "State", contact1.zip as "Zip", contact2.ubulletnqt as "Qty", contact2.ubullcolor as "BullColor", contact2.ubarcode as "Barcode", contact2.udelivery as "Delivery", contact2.uoutputdev as "OutputDev", contact2.utimedeliv as "Time", contact2.ucolor as "DelivColor", contact2.ucollated as "Collated", contact2.ustapled as "Stapled", case when contsupp.contsupref = 'Delivery Notes' then contsupp.notes end as "Deliverynotes", case when contsupp.contsupref = 'Cover Change Slip' then contsupp.notes end as "CoverChangeSlip" from Contact1 inner join contact2 on Contact1.Accountno = Contact2.Accountno inner join contsupp on Contact1.Accountno=Contsupp.Accountno where contact1.key5 not like '' and contsupp.contsupref='Delivery Notes' or contsupp.contsupref ='Cover Change Slip' order by contact1.key5 Thanks for your help
View Replies !
View List Of Prepared Statements
Is there a way to retrieve a list of the currently prepared statements? I am trying to understand the workings of an application but when I do a trace to find out what the application is doing to the dbs it shows lots of "exec sp_execute 4, 4, 2" lines. How do I find out what these exec statements are actually doing? TIA Nick
View Replies !
How Should I Write This Query Wiht Case Statements
Hi I have a stored procedure and i am trying to add case statements to them.. but i am getting an Error. which is Msg 125, Level 15, State 3, Procedure udf_EndDate, Line 34 Case expressions may only be nested to level 10. And This is my sproc-- ================================================ -- Template generated from Template Explorer using: -- Create Scalar Function (New Menu).SQL -- -- Use the Specify Values for Template Parameters -- command (Ctrl-Shift-M) to fill in the parameter -- values below. -- -- This block of comments will not be included in -- the definition of the function. -- ================================================ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author:<Author,,Name> -- Create date: <Create Date, ,> -- Description:<Description, ,> -- ============================================= Create FUNCTION [dbo].[udf_EndDate] (@PeriodId int) RETURNS datetime AS BEGIN DECLARE @Month int, @Year char(4) SELECT @Month = [Month], @Year = Cast([Year] as char(4)) FROM Period WHERE PeriodId = @PeriodId RETURN CASE @Month WHEN 1 THEN '1/31/' + @Year ELSE CASE @Month WHEN 2 THEN '2/28/' + @Year ELSE CASE @Month WHEN 3 THEN '3/31/' + @Year ELSE CASE @Month WHEN 4 THEN '4/30/' + @Year ELSE CASE @Month When 5 Then '5/31/' + @Year ELSE CASE @Month When 6 Then '6/30/' + @Year ELSE CASE @Month When 7 Then '7/31/' + @Year ELSE CASE @Month When 8 Then '8/31/' + @Year ELSE CASE @Month When 9 Then '9/30/' + @Year ELSE CASE @Month When 10 Then '10/31/' + @Year ELSE CASE @Month When 11 Then '11/30/' + @Year ELSE CASE @Month When 12 Then '12/31/' + @Year ELSE null END END END END END END END END END END END END END Any help will be appreciated. Regards Karen
View Replies !
SQL Statement, Adding Two COUNT/CASE Statements
SELECT COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END) AS [New Visitors], COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END) AS [Returning Visitors] FROM content_hits_tbl WHERE (hit_date BETWEEN DATEADD(mm, - 1, GETDATE()) AND GETDATE()) ======================= How do I add up both COUNT/CASE columns? Would it be: SUM([New Visitors] + [Returning Visitors]) AS Total I tried this and it doesn't work. I get invalid column names error for both. I have even tried: SUM([COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END)] + [COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END)]) AS Total You would think that there would be some gui functionality in VS08 that would do this... Thoughts are greatly appreciated! TT
View Replies !
Help With Stored Procedures Using IN / GROUP BY Statements
trying to get to the bottom of this for some time...... eventually tobe used with asp.heres the problemthe following rather complex SQL statement works fine via queryanalyser:SELECT TOP 100 tbl_LevelDetail.nvchLevelName AS DataLevelName,MAX(CASE tintDataFieldId WHEN '1' THEN CAST(nvchData AS int) ELSE 0END) AS 'Pos',MAX(CASE tintDataFieldId WHEN '2' THEN CAST(nvchData AS char) ELSE '' END) AS 'AreaName',MAX(CASE tintDataFieldId WHEN '3' THEN CAST(nvchData AS char) ELSE '' END) AS 'BDGName',MAX(CASE tintDataFieldId WHEN '4' THEN CAST(nvchData AS char) else '' END) AS 'Performance',MAX(CASE tintDataFieldId WHEN '5' THEN CAST(nvchData AS int) ELSE 0END) AS 'Qualifier'FROM tbl_Data, tbl_Levels, tbl_LevelDetail, tbl_LevelDetail AStbl_LevelDetail_ReportWHERE tbl_Data.nvchIncentiveId = 'MPW' AND tbl_Data.nvchPeriodId ='W27P'AND tbl_Levels.nvchIncentiveId = 'MPW' ANDtbl_LevelDetail.nvchIncentiveId = 'MPW'AND tbl_LevelDetail_Report.nvchIncentiveId = 'MPW' ANDtbl_Data.nvchDataLevelId = tbl_Levels.nvchDataLevelIdAND tbl_Levels.nvchDataLevelId = tbl_LevelDetail.nvchLevelIdAND tbl_Levels.nvchReportingLevelId =tbl_LevelDetail_Report.nvchLevelIdAND tbl_LevelDetail.nvchLevelTypeId = 2AND tbl_LevelDetail_Report.nvchLevelTypeId = 1AND tbl_Levels.nvchReportingLevelId IN ('a')GROUP BY tbl_Levels.nvchReportingLevelId, tbl_Levels.nvchDataLevelId,tbl_LevelDetail.nvchLevelName, tbl_LevelDetail_Report.nvchLevelNameORDER BY Pos, DataLevelNamereturns rows ok no problembut when trying to convert to a stored procedure i dont get anyresults:CREATE PROCEDURE usp_incmpwfilter_rs(@strPeriodID varchar ,@intLevelDetailID varchar,@intLevelReportID varchar,@strFilters varchar)ASset nocount onSELECT TOP 100 tbl_LevelDetail.nvchLevelName AS DataLevelName,MAX(CASE tintDataFieldId WHEN '1' THEN CAST(nvchData AS int) ELSE 0END) AS 'Pos',MAX(CASE tintDataFieldId WHEN '2' THEN CAST(nvchData AS char) ELSE '' END) AS 'AreaName',MAX(CASE tintDataFieldId WHEN '3' THEN CAST(nvchData AS char) ELSE '' END) AS 'BDGName',MAX(CASE tintDataFieldId WHEN '4' THEN CAST(nvchData AS char) else '' END) AS 'Performance',MAX(CASE tintDataFieldId WHEN '5' THEN CAST(nvchData AS int) ELSE 0END) AS 'Qualifier'FROM tbl_Data, tbl_Levels, tbl_LevelDetail, tbl_LevelDetail AStbl_LevelDetail_ReportWHERE tbl_Data.nvchIncentiveId = 'MPW' AND tbl_Data.nvchPeriodId =@strPeriodIDAND tbl_Levels.nvchIncentiveId = 'MPW' ANDtbl_LevelDetail.nvchIncentiveId = 'MPW'AND tbl_LevelDetail_Report.nvchIncentiveId = 'MPW' ANDtbl_Data.nvchDataLevelId = tbl_Levels.nvchDataLevelIdAND tbl_Levels.nvchDataLevelId = tbl_LevelDetail.nvchLevelIdAND tbl_Levels.nvchReportingLevelId =tbl_LevelDetail_Report.nvchLevelIdAND tbl_LevelDetail.nvchLevelTypeId = @intLevelDetailIDAND tbl_LevelDetail_Report.nvchLevelTypeId = @intLevelReportIDAND tbl_Levels.nvchReportingLevelId IN (@strFilters )GROUP BY tbl_Levels.nvchReportingLevelId, tbl_Levels.nvchDataLevelId,tbl_LevelDetail.nvchLevelName, tbl_LevelDetail_Report.nvchLevelNameORDER BY Pos, DataLevelNamethen call it by SQL statement:EXEC usp_incmpwfilter_rs 'W27P',2,1,'a'Returns no rows. This is the initial problem. Also there will beanother issue if i can get the above to work: the @strFilters cancontain multiple data, ie 'a','k'this works fine in the 1st sql statement ie: ANDtbl_Levels.nvchReportingLevelId IN ('a','k') but I dont know how topass as a parameter to the stored procedure. I cannot create temporarytables.i had not created the intial SQL statement, i am just trying toconvert it to a stored procedure which accepts thos parameters. thishas been a real headache for me, any help as always appreciatedgreatly.
View Replies !
Creating WHERE Clauses Based On IF (or CASE) STATEMENTS Transact-SQL
I am trying to create a stored procedure whose where clause isdependent on a parameter.If the parameter @myparam is null or '' then I want the where clause tobe one thing, else I want it to be a completely different thing. I cando it easily using iif but obviously that is not an option here...Here is what I have:Select @ FROM my table WHEREIF @myparam = '' or @myparam is null[MyField] = like '%'ELSEcharindex(@myparam,[MyField]) > 0)I have also tried variations of this and tried it using CASE. I keepgetting syntax errors. Do I have to write multiple SELECT statementsfor every possibility. If I can get this working the query willactually be a bit more complex, although it will follow this basicstructure...in other words, I'd rather not have to write multiplequeries when the only thing that is changing is the WHERE portion...Thanks!Ryan
View Replies !
Select List Contains More Items Than Insert List
I have a select list of fields that I need to select to get the results I need, however, I would like to insert only a chosen few of these fields into a table. I am getting the error, "The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns." How can I do this? Insert Query: insert into tsi_payments (PPID, PTICKETNUM, PLINENUM, PAMOUNT, PPATPAY, PDEPOSITDATE, PENTRYDATE, PHCPCCODE) SELECT DISTINCT tri_IDENT.IDA AS PPID, tri_Ldg_Tran.CLM_ID AS PTicketNum, tri_ClaimChg.Line_No AS PLineNum, tri_Ldg_Tran.Tran_Amount AS PAmount, CASE WHEN tln_PaymentTypeMappings.PTMMarsPaymentTypeCode = 'PATPMT' THEN tri_ldg_tran.tran_amount * tln_PaymentTypeMappings.PTMMultiplier ELSE 0 END AS PPatPay, tri_Ldg_Tran.Create_Date AS PDepositDate, tri_Ldg_Tran.Tran_Date AS PEntryDate, tri_ClaimChg.Hsp_Code AS PHCPCCode, tri_Ldg_Tran.Adj_Type, tri_Ldg_Tran.PRS_ID, tri_Ldg_Tran.Create_Time, tri_Ldg_Tran.Adj_Group, tri_Ldg_Tran.Payer_ID, tri_Ldg_Tran.TRN_ID, tri_ClaimChg.Primary_Claim, tri_IDENT.Version FROM [AO2AO2].MARS_SYS.DBO.tln_PaymentTypeMappings tln_PaymentTypeMappings RIGHT OUTER JOIN qs_new_pmt_type ON tln_PaymentTypeMappings.PTMClientPaymentDesc = qs_new_pmt_type.New_Pmt_Type RIGHT OUTER JOIN tri_Ldg_Tran RIGHT OUTER JOIN tri_IDENT LEFT OUTER JOIN tri_ClaimChg ON tri_IDENT.Pat_Id1 = tri_ClaimChg.Pat_ID1 ON tri_Ldg_Tran.PRS_ID = tri_ClaimChg.PRS_ID AND tri_Ldg_Tran.Chg_TRN_ID = tri_ClaimChg.Chg_TRN_ID AND tri_Ldg_Tran.Pat_ID1 = tri_IDENT.Pat_Id1 LEFT OUTER JOIN tri_Payer ON tri_Ldg_Tran.Payer_ID = tri_Payer.Payer_ID ON qs_new_pmt_type.Pay_Type = tri_Ldg_Tran.Pay_Type AND qs_new_pmt_type.Tran_Type = tri_Ldg_Tran.Tran_Type WHERE (tln_PaymentTypeMappings.PTMMarsPaymentTypeCode <> N'Chg') AND (tln_PaymentTypeMappings.PTMClientCode = 'SR') AND (tri_ClaimChg.Primary_Claim = 1) AND (tri_IDENT.Version = 0)
View Replies !
Concatenating Parameter Values && Text; Nested CASE Statements
Hello. I'm trying to reduce some code in my stored procedure and I'm running into lots of errors. I'm somewhat of a novice with SQL and stored procedures so any help would be beneficial. I have a SP that gets a page of user data and is also called when sorting by one of the columns (this data is placed in a repeater, btw). I quickly learned that I wasn't able to pass in string parameters the way I had hoped in order to handle the ORDER BY and direction (ASC/DESC) so I'm trying to work around this. So far I've tried the following with many errors.WITH Users AS ( SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN @OrderBy='FirstName' AND @Direction='DESC' THEN (FirstName + ' DESC') WHEN @OrderBy='FirstName' THEN FirstName WHEN @OrderBy='LastName' AND @Direction='DESC' THEN (LastName + ' DESC') WHEN @OrderBy='LastName' THEN LastName END ) AS Row, UserID, FirstName, LastName, EmailAddress, [Role], Active, LastLogin, DateModified, ModifiedBy, ModifiedByName FROM vRF_Users ) SELECT UserID, FirstName, LastName, EmailAddress, [Role], Active, LastLogin, DateModified, ModifiedBy, ModifiedByName FROM Users WHERE Row BETWEEN @StartRowIndex AND @EndRowIndex I've tried a combination of similar things with parenthesises, without, doing "THEN FirstName DESC" without concatenating anything, etc. I also tried: DECLARE @OrderByDirection varchar(32) DECLARE @DESC varchar(4) SET @DESC = ' DESC' IF @Direction = 'DESC' BEGIN SET @OrderByDirection = (@OrderBy + @DESC) END And then writing my case statemet like this:ORDER BY CASE WHEN @Direction='DESC' THEN @OrderByDirection ELSE @OrderBy ENDObviously this didn't work either. Is there any way to gracefully accomplish this or do I just have to use a bunch of if/else statements and lots of redundant code to evaluate all my @OrderBy and @Direction parameters??? Thanks in advance, Jen
View Replies !
Trying To Get - List Of Brokers With One Case Only In Last 9 Months
I have a problem where I need to return a list of Brokers that have had only one case and that case was in the last nine months, the script below was returning appropriate numbers until I amended it to add the date of that case (cdateReceived) and the related join. There were 470 rows returned before the addition of the cdateReceived and 1780 rows after. Ordinarily you would expect the dataset to grow with the addition of a join on a one-to-many realtionship but the criteria should be limiting the resuilts to be brokers with only one case!!! It should not then increase the number of rows. What am I mis-understanding? SELECT TOP 100 PERCENT dbo.brokerDetails.bFirstname + ' ' + dbo.brokerDetails.bSurname AS Broker, dbo.brokerCompany.companyName, dbo.brokerCompany.cTown, dbo.brokerCompany.cPostCode, ISNULL(dbo.brokerParent.pName, 'DIRECTLY AUTHORISED') AS Network, dbo.cases.cDateReceived FROM dbo.brokerDetails INNER JOIN dbo.brokerCompany ON dbo.brokerDetails.bCompany = dbo.brokerCompany.companyID LEFT OUTER JOIN dbo.brokerParent ON dbo.brokerCompany.cNetworkID = dbo.brokerParent.parentID INNER JOIN dbo.cases ON dbo.brokerDetails.BrokerID = dbo.cases.BrokerID WHERE (dbo.brokerDetails.brokerID IN (SELECT TOP 100 PERCENT brokerID FROM dbo.cases WHERE (cDateReceived < DATEADD(mm, - 9, GETDATE())) AND (Spiked = 0) AND (IsDirect = 0) GROUP BY brokerID ORDER BY brokerID ) ) AND (dbo.brokerDetails.brokerID IN (SELECT TOP 100 PERCENT brokerID FROM dbo.cases WHERE (spiked <> 1) AND (IsDirect = 0) GROUP BY brokerID HAVING count(caseID) =1 ORDER BY brokerID ) ) ORDER BY dbo.brokerDetails.bFirstname + ' ' + dbo.brokerDetails.bSurname
View Replies !
Trying To Get - List Of Brokers With One Case Only In Last 9 Months
I have a problem where I need to return a list of Brokers that have had only one case and that case was in the last nine months, the script below was returning appropriate numbers until I amended it to add the date of that case (cdateReceived) and the related join. There were 470 rows returned before the addition of the cdateReceived and 1780 rows after. Ordinarily you would expect the dataset to grow with the addition of a join on a one-to-many realtionship but the criteria should be limiting the resuilts to be brokers with only one case!!! It should not then increase the number of rows. What am I mis-understanding? SELECT TOP 100 PERCENT dbo.brokerDetails.bFirstname + ' ' + dbo.brokerDetails.bSurname AS Broker, dbo.brokerCompany.companyName, dbo.brokerCompany.cTown, dbo.brokerCompany.cPostCode, ISNULL(dbo.brokerParent.pName, 'DIRECTLY AUTHORISED') AS Network, dbo.cases.cDateReceived FROM dbo.brokerDetails INNER JOIN dbo.brokerCompany ON dbo.brokerDetails.bCompany = dbo.brokerCompany.companyID LEFT OUTER JOIN dbo.brokerParent ON dbo.brokerCompany.cNetworkID = dbo.brokerParent.parentID INNER JOIN dbo.cases ON dbo.brokerDetails.BrokerID = dbo.cases.BrokerID WHERE (dbo.brokerDetails.brokerID IN (SELECT TOP 100 PERCENT brokerID FROM dbo.cases WHERE (cDateReceived < DATEADD(mm, - 9, GETDATE())) AND (Spiked = 0) AND (IsDirect = 0) GROUP BY brokerID ORDER BY brokerID ) ) AND (dbo.brokerDetails.brokerID IN (SELECT TOP 100 PERCENT brokerID FROM dbo.cases WHERE (spiked <> 1) AND (IsDirect = 0) GROUP BY brokerID HAVING count(caseID) =1 ORDER BY brokerID ) ) ORDER BY dbo.brokerDetails.bFirstname + ' ' + dbo.brokerDetails.bSurname
View Replies !
Group With A Case?
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 Replies !
List Group With Different Datasets
I am looking into report design with the Reporting Services, but I am stuck at a quite early stage. I try to report sales data. My (example) sales do have three main attributes: The date of the sale, the product sold, and the shop location. I understand that the LIST - item can be used to create what Access Reports did using sub reports: repeat a specific section for all items in the range. I am thinking of a report that has a section for each location, I managed to create this "group" by using a list item on the shop name. Within the group I would like to see two charts, one that shows the sales by day of month (independent of product sold) and one pie that shows the distribution of products for the whole month (independent of day of month). I cannot get that all in one dataset, as the one set has another grouping (by day, ignore type) than the other (by type, ignore day). I can create 2 or 3 datasets with the requiring grouping, one being on shops, the second on days, the third on product, but I do not see a way to connect the group property of the repeating list section to the other datasets ... What would be the correct way to create such a report?
View Replies !
Page 2 - Trying To Get - List Of Brokers With One Case Only In Last 9 Months
Well I agree with you about "Order By" having no value in the subquery, its a silly slip from clarity caused after ordering the subquery when it was run in isolation as an individual query to verify the dataset. However removing the ORDER BY from the subquery allows the removal of TOP from the subquery but not the highest level query as I need to keep some order in the madness. Quote: Originally Posted by r937 ORDER BY makes absolutely no sense in a subquery take it out and i'll bet EM doesn't stick TOP 100 PERCENT in there any more what it's trying to do is overcome the silliness of ORDER BY in a subquery with its own silliness kind of like acid/base, yin/yang, ...
View Replies !
USING 'CASE' TO GROUP DATA
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 Replies !
Question Regarding CASE And GROUP BY
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 Replies !
Need Some Assistance With A Group By Case
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 Replies !
Group Case Sensitive
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 Replies !
Group By Case Statement
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 Replies !
How To Group/list Top 3 Of Each Category W/o Using Union?
Hello,So my table contains say 100,000 records, and I need to group thecategories in fld1 by the highest count of subcategories. Say fld1contains categories A, B, C, D, E.All of these categories contain subcategories AA, AB, AC, AD,...AJ, BA,BB...BJ, CA, CB, CC...CJ, etc in fld2.I am counting how many subcategories are listed for each category. LikeA may contain 5 of AA, 7 of AB, 3 of AC, 11 of AD...1 for the rest and20 of AJ. B may contain 2 of BA, 11 of BB, 7 of BC, and 1 for the rest.I want to pick up the top 3 subcategory counts for each category. Wouldlook like this:Cat SubCat CountA AJ 20A AD 11A AB 7B BB 11B BC 7B BA 2So event though each category contains 10 subcategories, I only want tolist the top 3 categories with the highest counts as above. If I justdo a group by and sort I can get this:Cat SubCat CountA ... ...AAAAAA...B ... ...BBBBB...But I just want the top 3 of each category. The only way I can think ofto do this is to query each category individually and Select Top 3, andthen Union these guys into one query. The problem is that I have tohardcode each category in the Union query. There may be new categoristhat I miss. Is there a way to achieve what I want without using Union?Thanks,Rich*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View Replies !
Concatenate List Of Values Under A Group
I have the following dataset: State ZIP Homes Schools WA 98007 2000 4 WA 98052 3000 5 WA 98079 2000 3 Now if I have set the group by expression on State but as display if I want to show it as €œ[98007, 98052, 98079]€? how can I accomplish this. My report needs to show: State Homes Schools [98007, 98052, 98079] 7000 12 Any help will be greatly appreciated
View Replies !
Dynamic CASE Statement Based On List Of Dates
I have the following table of data. I need to take a date from a large table and do the following case:CASEWhen date < date(0) Then '0'When date between date(0) and date(1) Then '1'When date between date(1) and date(2) Then '2'When date >= date(3) Then '3'What I need is to be able to read all the dates the the Date table, sort then chronologically, and build the dynamic CASE statement so that the first When statement is < Date(0) and the last When statement is >= Date(Last)I hope I am making sense. Dates will be added to the table about once a year or so and I don't want to keep going back into the sql function and rewrite it with the latest date. Any ideas how to manipulate these dates into a case statement? Don't worry about the second table below. I just wanted you to see why I need to return an int from the Case function.thanksMilton Dates Table Date 4/1/2003 1/1/2006 4/2/2007 Fee Table Date Period Class Fee 1 Daily True 329 1 Half Day True 178 1 OT True 49 1 Hourly True 41 1 Daily False 156 1 Half Day False 86 1 OT False 27 1 Hourly False 19 2 Daily True 355 2 Half Day True 192 2 OT True 50 2 Hourly True 44 2 Daily False 171 2 Half Day False 92 2 OT False 28 2 Hourly False 21 3 Daily True 364 3 Half Day True 197 3 OT True 51 3 Hourly True 45 3 Daily False 175 3 Half Day False 94 3 OT False 29 3 Hourly False 21
View Replies !
Transact-SQL Help - CASE Statement And Group By
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 Replies !
|