Please read the attached txt file.The challenge is to summarize the data per patient but only as / if the consultant changes.This is giving me sleepless nights. I've tried ranking functions,self joins and iterative cte's to no availThanks for your help
↧
Set based super challenge
↧
error with stored procedure
when i execute the SP with data parametersUSE [ABC]GODECLARE @return_value intEXEC @return_value = [dbo].[test] @QTRSTRTDATE = N'select CONVERT(datetime,DATEADD("M", DATEDIFF("M", 0, GETDATE()), 0),120)', @QTRENDDATE = N'select CONVERT(datetime,DATEADD("M",DATEDIFF("M",-1, GETDATE()),-1),120)'SELECT 'Return Value' = @return_valueGOi get the below error..[i]Msg 8114, Level 16, State 5, Procedure usp_MarketingAccountLevel_test, Line 0Error converting data type nvarchar to datetime.(1 row(s) affected)[/i]Any help.
↧
↧
sql query to find the difference in values from previous month
I have my sql tables and query as shown below :[code="sql"]CREATE TABLE #ABC([Year] INT, [Month] INT, Stores INT);CREATE TABLE #DEF([Year] INT, [Month] INT, SalesStores INT);CREATE TABLE #GHI([Year] INT, [Month] INT, Products INT);INSERT #ABC VALUES (2013,1,1);INSERT #ABC VALUES (2013,1,2);INSERT #ABC VALUES (2013,2,3);INSERT #DEF VALUES (2013,1,4);INSERT #DEF VALUES (2013,1,5);INSERT #DEF VALUES (2013,2,6);INSERT #GHI VALUES (2013,1,7);INSERT #GHI VALUES (2013,1,8);INSERT #GHI VALUES (2013,2,9);INSERT #GHI VALUES (2013,3,10);[/code]My current query isI have @Year and @Month as parameters , both integers , example @Year = '2013' , @Month = '11'[code="sql"]SELECT T.[Year], T.[Month] -- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run) , (SELECT SUM(Stores) FROM #ABC WHERE [Year] = T.[Year] AND [Month] = T.[Month]) AS [Sum_Stores], (SELECT SUM(SalesStores) FROM #DEF WHERE [Year] = T.[Year] AND [Month] = T.[Month]) AS [Sum_SalesStores], (SELECT SUM(Products) FROM #GHI WHERE [Year] = T.[Year] AND [Month] = T.[Month]) AS [Sum_Products]FROM ( -- this selects a list of all possible dates. SELECT [Year], [Month] FROM #ABC where [Year] = @Year and [Month] = @Month UNION SELECT [Year], [Month] FROM #DEF where [Year] = @Year and [Month] = @Month UNION SELECT [Year], [Month] FROM #GHI where [Year] = @Year and [Month] = @Month) AS T; [/code]Which returns[code="plain"]+------+-------+------------+-----------------+--------------+| Year | Month | Sum_Stores | Sum_SalesStores | Sum_Products |+------+-------+------------+-----------------+--------------+| 2013 | | | | || 2013 | | | | || 2013 | | | | |+------+-------+------------+-----------------+--------------+[/code]What I want to do is to add more columns to the query which show the difference from the last month. as shown below. Example : The Diff beside the Sum_Stores shows the difference in the Sum_Stores from last month to this month.Something like this :[code="other"]+------+-------+------------+-----------------+-----|-----|---+-----------------| Year | Month | Sum_Stores |Diff | Sum_SalesStores |Diff | Sum_Products |Diff|+------+-------+------------+-----|------------+----|---- |----+--------------|| 2013 | | | | | | | || 2013 | | | | | | | || 2013 | | | | | | | |+------+-------+------------+-----|------------+--- |-----|----+---------| ----[/code]Can anyone tell me how I can modify this to achive my goal.
↧
display columns with no data
Newbie..sorry, posted this somewhere else, but couldn't find it. Trying to get the PSI Outcome, Expected, and PSIIndex every month whether it has data or not. Created a CTE and left outer joined with PSI table, but it's still not pulling every month for every PSIKey. Any help is appreciated. Thank you. Table schematicsdi.DivisionRegion,intP.PSIKey,intP.PSIOutcome,intP.PSIExpected,int---------------------------------------------------------------------------define start and end limitsDeclare @todate datetime, @fromdate datetimeSelect @fromdate='2013-01-01', @todate='2013-02-01' ;With cte as( Select @fromdate as Date union all Select dateadd(day, 1, Date) from cte da where Date < @todate) select di.DivisionRegion,month(d.date) as month,year(d.Date) as Year,p.PSIKey,ps.PSIname,sum(p.PSIOutcome) as PSIOutcome,isnull(SUM(p.PSIExpected),0) as Expected,isnull(((sum([PSIOutcome]))/(sum ([psiexpected]))),0) as PSIIndexfrom cte dleft outer join quality.dbo.Fact_PatientSafetyIndicators p on cast(p.DischargeDateTime as date) = d.Dateleft outer join LukesReporting.UserView.vwAccount a on a.OriginAccountId = p.VisitIDleft outer join Quality.dbo.Dim_PatientSafetyIndicators ps on ps.PSIKey = p.PSIKeyleft outer join LukesReporting.UserView.vwDivisionCode di on di.DivisionCode = a.DivisionCodewhere p.DivisionCode in ('$','1','2','{','#','L','6','t','[') and p.PSIKey in ('1','2','3','4' ,'5','6','7','8','12','13','14','15','16','17','18','19','20','21')group by di.divisionregion,month(d.date),year(d.date),p.PSIKey,ps.PSINameorder by di.divisionregion,year(d.date),month(d.date),p.PSIKey,ps.PSIName
↧
FileStream Enabled Columns
My Filestream enabled column will store Doucments.I want to replicate this column.SQL Server 2012 environment with Cluster.My question is that "Filestream Data Container is same for both publisher server and Subscriber server", so can i insert using T-SQL code for Subscripber side as they are Cluster [able to access same disk]"?Thanks,Sasidhar P
↧
↧
select house_no order
i have table coloum like below[b]House_no[/b]3-4-53 . HYDERABAD3-4-199/1.ASVV3-4-vizag3-4-22,nagar3-4-45.old colony3-4-66/993-4-2/42-43-5-hasd3-6van4-5-123asvr select house no orderi want output like below format[b]House_no[/b]2/42-43-4-3-4-vizag3-4-22,nagar3-4-45.old colony3-4-53.HYDERABAD3-4-66/993-4-199/1.ASVV3-5-hasd3-6van4-5-123asvr
↧
select quarie between houseno ..........
i have table like belowHouse_No4-12-10004-12-55/b4-12-1456/b/c4-12-124-12-13984-12-234-12-984-12-14991-4-333-9-552-5-89/3i want out put like select only in between houseno ' 4-12-1000' to '4-12-1500'EX-House_No4-12-10004-12-13984-12-1456/b/c4-12-1499plz write sql quarie...........
↧
sp with one or more input parameters
Hi,I've been tasked with creating a stored procedure which will be executed after a user has input one or more parameters into some search fields. So they could enter their 'order_reference' on its own or combine it with 'addressline1' and so on. What would be the most proficient way of achieving this? I had initially looked at using IF, TRY ie:[code="sql"] IF @SearchField= 'order_reference' BEGIN TRY select data from mytables END TRY[/code]However I'm not sure this is the most efficient way to handle this.Thanks for any advice
↧
Exec producing table out of scope
Hi,I am generating some dynamic sql which I would like to run and return the data from, however when I run EXEC(@TEMP_TABLE_STRING) it cannot return the table I think because it is out of scope.Is there a way around this.[code="sql"]declare @Tablename VARCHAR(150) = 'TEMP_LOCATIONS'declare @FilterClause VARCHAR(512)=NULLdeclare @Classes VARCHAR(100)=NULLdeclare @IsExcel BIT = 1 DECLARE @SQL Nvarchar(MAX) = '' SET NOCOUNT ON; DECLARE @TEMP_TABLE_STRING NVARCHAR(MAX)SET @TEMP_TABLE_STRING = CASE WHEN @IsExcel = 1 THEN 'SELECT TOP(65000) WC.* 'ELSE'SELECT WC.* 'END+ ' INTO #YourTable FROM dbo.V_ALLCLASSESWCOMMENTS wc JOIN '+ @Tablename +' loc ON wc.LOCATION_ID = loc.LOCATION_ID '+ CASE WHEN @FilterClause IS NOT NULL THEN ' WHERE '+ @FilterClause ELSE '' ENDEXEC(@TEMP_TABLE_STRING)SELECT * FROM #YourTable[/code]Returning the error:Msg 208, Level 16, State 0, Line 22Invalid object name '#YourTable'.Many Thanks for your help in advance.Oliver
↧
↧
How to combine data from different tables using a query
I have a set of tables that look like what I have shown below.Could you let me know how I can achive the desired output ?[code="sql"] CREATE TABLE #ABC([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductA INT); CREATE TABLE #DEF([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductB INT); CREATE TABLE #GHI([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductC INT); INSERT #ABC VALUES (2013,1,'PPP',1); INSERT #ABC VALUES (2013,1,'QQQ',2); INSERT #ABC VALUES (2013,2,'PPP',3); INSERT #DEF VALUES (2013,1,'QQQ',4); INSERT #DEF VALUES (2013,1,'RRR',5); INSERT #DEF VALUES (2013,2,'PPP',6); INSERT #GHI VALUES (2013,1,'QQQ',7); INSERT #GHI VALUES (2013,2,'RRR',8); INSERT #GHI VALUES (2013,3,'PPP',9); INSERT #GHI VALUES (2013,3,'QQQ',10);[/code] I have a query currently that looks like this . @Month and @Year are supplied as parameters[code="sql"] SELECT -- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run) (SELECT SUM(SalesofProductA) FROM #ABC WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductA] ,(SELECT SUM(SalesofProductB) FROM #DEF WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductB] ,(SELECT SUM(SalesofProductC) FROM #GHI WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductC] FROM ( -- this selects a list of all possible dates. SELECT [Year],[Month] FROM #ABC where Year = @Year and Month = @Month UNION SELECT [Year],[Month] FROM #DEF where Year = @Year and Month = @Month UNION SELECT [Year],[Month] FROM #GHI where Year = @Year and Month = @Month ) AS T;[/code]Right now I see an output like this : for a particular value of @Month and @Year [code="other"] SalesofProductA, SalesofProductB, SalesofProductC [/code]What I would like to see is : [code="other"] [Customer],SalesofProductA, SalesofProductB, SalesofProductC [/code]Does anyone know how it can be done ?
↧
ORDER BY ROUNDS - Sanity Check
I got this working but thought I would share it with you all. I have this query[code="sql"] DECLARE @WorkingStartDate date = '1/1/2001' DECLARE @WorkingEndDate date = '11/30/2013' SELECT PerformanceDataType_ID,PerformanceDataSubType_ID,PerformanceDataTypeName, [2001] AS Year2001,[2002] AS Year2002,[2003] AS Year2003,[2004] AS Year2004,[2005] AS Year2005,[2006] AS Year2006, [2007] AS Year2007,[2008] AS Year2008,[2009] AS Year2009,[2010] AS Year2010,[2011] AS Year2011,[2012] AS Year2012, [2013] AS Year2013 FROM (SELECT PerformanceDataType_ID ,PerformanceDataSubType_ID ,PerformanceDataTypeName ,PerformanceYear ,CAST(IndexValue AS Decimal(36,18)) AS IndexValue FROM [Datawarehouse].[dbo].[tblGipPerformanceData] WHERE PerformanceDataValue IS NOT NULL AND StartDate >= @WorkingStartDate AND EndDate <= @WorkingEndDate) AS SourceTable PIVOT ( Datawarehouse_Reporting.dbo.GeometricLinking(IndexValue) FOR PerformanceYear IN ([2001],[2002],[2003],[2004],[2005],[2006],[2007],[2008],[2009],[2010],[2011],[2012],[2013]) ) AS PivotTable ORDER BY PerformanceDataTypeName [/code]When I ran this code it would round my values at the 6th decimal place. I did all sorts of crazy casting, converting, and creating other tables to stop this from happening but got absolutely nowhere. Then I got the idea to just remove the order by part of the query (I was grasping at straws at this point) and the values came down as expected. Has anyone else come across this? Is this an undocumented feature? Maybe a bug?Paul
↧
Doubt in error handling
Hi There,Please find the following query,[code="sql"]begin tryselect top 10* from Sampletable(nolock) end trybegin catchprint('table not available')end catch [/code]Actually above table is not available in the database. So I expect my query would result "table not available" but it results Msg 208, Level 16, State 1, Line 3Invalid object name 'vw_cdr'.Please explain why try catch not working?
↧
Add Total to the query
Fi,I have a table with the Group name and Total Count by group . I need to add a 'Total' and summation of all counts at the end . CREATE TABLE #TempTable (GroupName VARCHAR(10),NumberOfCases INT )INSERT INTO #Temp Table (GroupName,NumberOfCases)VALUES ('Grp A',10)INSERT INTO #Temp Table (GroupName,NumberOfCases)VALUES ('Grp B',20)SELECT * from #TempTableI want the result to be like the below :Grp A 10Grp B 20Total 30Thanks,PSB
↧
↧
Substring with patindex
Hi Everyone I am having an syntax issues I am not able to work out. I have a value in a column '01-08-087-0101W5'I would like to break this value down into 5 different columnsthe column will be broken down at the dashes , so the 5 columns will have values like01080871015I would also like to trim any leading 0's in the above values. i have been trying the followingSUBSTRING(column1,patindex('%[^0]%',column1) ,2) AS FROM_TWPThanks.Edit, I made a mistake in the posting. I needed 5 not 4 columns
↧
date between in procedure
hi every one,i need procedure query for two date between fromdate and todatepls. i need helpalter procdure datedeclare @Fromdate varchar(10)declare @todate varchar(10)as beginselect * from master where convert(varchar(10),@Fromdate,121) between CONVERT(varchar(10),@Todate,121) and CONVERT(varchar(10),rr.Original_Date,121)endThanksRajnidas
↧
error in procedure
hi every one, i was not able to solve pls i need help. while using store procedure in report getting error as mentioned below !Cannot resolve the collation conflict between "Latin1_General_CI_AI" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.ThanksRajnidas
↧
Need to find continues number ranges
Hi There,Please consider the following data [code="sql"]create table #sampletbl(Category varchar(100),Numbers varchar(100),Status varchar(100))insert into #sampletbl values ('A','29710000001','0')insert into #sampletbl values ('A','29710000002','0')insert into #sampletbl values ('A','29710000003','0')insert into #sampletbl values ('A','29710000004','0')insert into #sampletbl values ('A','29710000005','0')insert into #sampletbl values ('A','29710000006','1')insert into #sampletbl values ('A','29710000007','0')insert into #sampletbl values ('A','29710000008','0')insert into #sampletbl values ('A','29710000009','1')insert into #sampletbl values ('A','29710000010','0')insert into #sampletbl values ('A','29710000011','0')insert into #sampletbl values ('A','29710000012','0')insert into #sampletbl values ('A','29710000013','0')insert into #sampletbl values ('A','29710000014','0')insert into #sampletbl values ('A','29710000015','0')insert into #sampletbl values ('A','29710000016','0')insert into #sampletbl values ('A','29710000017','0')insert into #sampletbl values ('A','29710000018','0')insert into #sampletbl values ('A','29710000019','0')insert into #sampletbl values ('A','29710000020','1')[/code]if status = 0 then unused status = 1 then usedi need to find 10 continues unused numbers This is the sample data. In live I'm having plenty of data like that . So quite complex. note : In real world I need to find the 1000 continues number ranges pls help....
↧
↧
find the missing nos in the continues series
Hi There,Category NosA 1A 2A 3A 5A 6A 9A 10B 23B 24B 25B 27B 28B 29B 31Consider the above data...I need following output... Help me with query ..Category Min Range Max RangeA 1 3A 5 6A 9 10B 23 25B 27 29B 31 31Logic Behind : if any number is missing in the continues series the return the min and max of number in that range.Thanks In advance
↧
find first value greater than a specific value
I need a query to get the first value greater than a specific threshold valueLoadTemp1 LoadTemp2 LoadTemp3 LoadTemp4 TimeStamp300 200 100 320 12-10-2013 13:30:29100 250 113 340 12-10-2013 14:20:12114 339 209 345 12-10-2013 14:45:01I need to get the first value >= 340 thresholdI need to make a Benchmark on when the first LoadTemp crosses Threshold of 340 and capture the time.Please help.
↧
Conversion failed when converting the varchar value 'Coolant Quick Disconnect' to data type int
I'm having a problem with inserting test data into a table. I am getting the error listed in the title. I have done a lot of googling without finding a solution.Within in Visual Studio 2012 solution, I have several projects, one of which is a Database project. I am defining several tables. The one in question is:[code="sql"]CREATE TABLE [dbo].[tblKppHierarchyPcl]( [ID] NUMERIC(18,0) NOT NULL, [Name] VARCHAR(500), [PartStructureKey] NUMERIC(18,0) NOT NULL, [PartNumber] VARCHAR(500) NOT NULL, [ParentPartNumber] VARCHAR(500) NULL, [TargetCost] DECIMAL(30,4) NULL, [UnitCost] DECIMAL(30,4) NULL, [CostMaturityID] INT NULL, [Ratio] DECIMAL(16,2) NULL, [Contribution] DECIMAL(16,2) NULL, [ChildPartTargetWeight] NUMERIC(18,2) NULL, [ChildPartWeight] NUMERIC(18,2) NULL, CONSTRAINT [FK_tblKppHierarchyPcl_tblCostMaturity] FOREIGN KEY (CostMaturityID) REFERENCES tblCostMaturity([CostMaturityID]) )[/code]Using a Script.PostDeployment1.sql file, I am trying to populate the table with test data like so:[code="sql"]INSERT INTO [dbo].[tblKppHierarchyPcl] ([ID] ,[Name] ,[PartStructureKey] ,[PartNumber] ,[ParentPartNumber] ,[TargetCost] ,[UnitCost] ,[CostMaturityID] ,[Ratio] ,[Contribution] ,[ChildPartTargetWeight] ,[ChildPartWeight]) VALUES(61090,'Coolant Quick Disconnect',125216,'FS-252-6FO','H432677DB-1',27.03,70.61,2,2.61,0.01,0,NULL)[/code]I am trying to push the data to the database via SqlPublish.My problem is this: When the post-deployment script tries to insert the data, I get the following error:[b]Error SQL72014: .Net SqlClient Data Provider: Msg 245, Level 16, State 1, Line 76 Conversion failed when converting the varchar value 'Coolant Quick Disconnect' to data type int.[/b]So it has a problem with inserting 'Coolant Quick Disconnect' into the Name column. The Name column is CLEARLY a varchar column but somehow it thinks it's an int column.Any ideas?
↧