This is a pretty simple query that tracks 'yesterdays' apply clicks on our website.
SELECT MIN(A.hitDate) AS minDate, D.AffiliateName, B.ProdType, COUNT(DISTINCT A.ipAddress) AS TOTAL FROM ArchiveApplyTracking A LEFT OUTER JOIN Configuration.dbo.Affiliates D ON A.affiliateID = D.AffiliateID LEFT OUTER JOIN Incoming C ON A.campaignID = C.ID LEFT OUTER JOIN Configuration.dbo.ProductType B ON A.productTypeID = B.ProdNo WHERE (A.hitDate >= DATEADD(d, DATEDIFF(d, 0, GETDATE() - 1), 0)) AND (A.hitDate < DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)) AND (A.deal = 1) AND (A.ipAddress NOT IN (SELECT ipAddress FROM [Tracking].[dbo].ipTracking)) AND (B.ProdType NOT LIKE 'refused%') AND (D.AffiliateName LIKE 'ARROW%') AND (B.ProdType NOT LIKE '%prequalify%') GROUP BY D.AffiliateName, B.ProdType ORDER BY D.AffiliateName
No problem there, that's fine.
But how can i put a simple date range interface on my published report so users can say "get me the stats from 04/09/2005 to 20/09/2005, which then runs the query?
I am working with a vendor application called Cisco Unified Attendant Console - it operates on a Windows server with a SQL express database. The CUPs function of the application needs to reference a "contact" field with only the user portion of the contact's email address - generally, the contact's User ID will match the user portion of their email address, however, for this customer it does not (they use the employee number as the User ID and firstname.lastname as user portion of the email address.
Writing a script to accomplish the following:
The dbo.Contact_Properties table of the ATTCFG database has the following fields that we can work with:
- First_Name - Last_Name - Email - User_Field_2 - Contact_Unique_Ref (appears to be the field that ties all other contact tables together ?)
Is it possible to create a script that could run daily to either, combine the First_Name and Last_Name fields (with a period between) and populate the User_Field_2 field for each user, or populate the User_Field_2 field with everything before the @ symbol in the Email field for each user?
Also, by default the servers that this application is installed on does not have SQL Server Management Studio installed - is it possible to accomplish with PowerShell script triggered from the Windows Scheduler?
SELECT 'abc' + '-' + CAST(SeqNo AS VARCHAR) + '-' + CAST(Payment AS VARCHAR) FROM abc WHERE SeqNo = 1 UNION SELECT 'def' + '-' + CAST(SeqNo AS VARCHAR) + '-' + CAST(Payment AS VARCHAR) FROM def WHERE SeqNo = 1 abc-1-200.00 abc-1-500.00
As you can see since 1 doesn't exists in table 'def' nothing is returned as expected. However, if a row isn't returned I want to be able to enter my own row such as
I'm trying to add random dates to date column in existing table, but these need to be week days (Mon-Fri).I'm a beginner in TSQL, worked with MS Access many years - in Access I used to do something a bit different:
DateAdd("d",(Int((5*Rnd([ID]))+1)),#31/08/2015#) Table had ID, I gave a date it would start from (31/08/2015) and then range of ID to apply new date: UPDATE table1 SET table1 .date = DateAdd("d",(Int((5*Rnd([ID]))+1)),#31/08/2015#) WHERE (((table1 .ID) Between 1 And 5456));
This was applying random dates in range of 31/08/2015 + 5 days, so I could give a starting date of Sunday to get random dates populated over given IDs from Monday to Friday.Now, how can I do it in TSQL?I have a table with ID and dates column. I would like to apply new random dates from some range, but making sure they will be week days.
Our server has integrated security setup, upon startup of the server, we have a continuous flow of error msg: Login Failed: Reason: User '_' not defined as a valid user of trusted connection. The timing of these messages only around 30 seconds apart The only incident from Technet I can find is Q186314, but we don't have replication setup, anyone knows where I can look into ? I recycle the server but didn't help. I appreciate any help I can get .. Thanks.
In the table, there is a record which has several field. every month, the function will create a same record. that means, the first month, one record. the secord month, two reocrds, ..... for a years. will have same 12 record. so what function can do this? Thanks.
How can I automatically change records by a specific date specified inside the record. An example would be the way ebay sales work. How does ebay have the status of an item change to closed, at the time inside the item record of the database.
I know i could use triggers or something to check the current date against the enddate everytime the record is accessed, but is there a more efficient method?
Was wondering if there is easy anyway to autopopulate a field by pulling a value from a field in the previous record?
For example, I have a table with fields name "Dist_From" and "Dist_To". When I add a new record I would like it to populate the "Dist_From" field with the "Dist_to" value from the previous record.
Sql is not a strong point with me so I'm just going to throw this out there. I have a stored procedure that updates the quantity in my 'CartItems' table. Is there a way to have something else happen within the stored procedure that will update another field based on other parts of the record? There is a 'lineTotal' field that I need to equal the 'pounds * itemSell' fields which are both fields within this record. CREATE PROCEDURE UpdateCartItem(@cartItemID Int,@newQuantity numeric(9))ASUPDATE CartItems Set quantity = @newQuantityWHERE cartItemID = @cartItemIDGO
The "Field name" value is 875 and i need to edit the value to 0(zero).
It appears an error -
---------------------------- Msg 260, Level 16, State 1, Line 1 Disallowed implicit conversion from data type varchar to data type money, table 'dbname.dbo.table name', column 'field name'. Use the CONVERT function to run this query. -----------------------------
So if i change the data type from right click design menu to nvarchar(50) can it be edited from the command that i used above?
I HAVE THIS SQL STATEMENT WHICH GET THE MIN(AMOUNT) and MAX(AMOUNT) and DISPLAY IT IN A SINGLE ROW. HOW CAN I GET THE RECORD BEFORE THE MAX (AMOUNT) INBETWEEN DATES IN CASE THERE ARE 4 RECORDS WITH SAME EMPLOYEENO IN THE DATE RANGE SPECIFICIED ? THIS IS SORTED BY EMPLOYEENO AND STARTDATE DESC
SELECT EmployeeNo, StartDate AS StartDate, MIN(Amount) AS oldsalary, EndDate AS EndDate, BenefitCode, (SELECT TOP 1 MAX([amount]) FROM EMPBENEFITS T2 WHERE T2.employeeno = T.employeeno AND startdate >= '2001-06-01' AND startdate <= '2007-06-02') AS newsalary FROM dbo.empBenefits T WHERE (StartDate IN (SELECT TOP 1 ([startdate]) FROM EMPBENEFITS T1 WHERE T1.employeeno = T.employeeno AND Benefitcode <> 'HON' AND startdate >= '2001-06-01' AND startdate <= '2007-06-02')) GROUP BY EmployeeNo, Amount, BenefitCode, StartDate, EndDate, Amount ORDER BY EmployeeNo, StartDate DESC
I am currently using this SQL code to capture some records over the last 2 months and it has been working great. I am now being asked if I can change this code with specifications:
1) Scan the records in the system until the count (*) as Volume reaches 30 because they prefer that as a denominator when figuring an average
2) Only run the scan for a maximum of 6 months.
So, there will most likely be some records that do not reach a volume number of 30 in this date range. In this instance we will just take the maximum volume number reached at 6 months.
So, how can I write this so it will build the file each time a record has reached the maximum of 30 and keep scanning back until we reach 6 months? If someone could lead me in the right direction on the proper order of the methodology in my code to accomplish these results it would be greatly appreciated. Desperate!
declare @startdate smalldatetime, @enddate smalldatetime , @month int, @year int
pe1.patev_loc_id as LocID, pp_cproc_id_r as ProcID, count (*) as Volume, sum (datediff (mi, pe1.patev_event_time, pe2.patev_event_time)) as Minutes, sum (datediff (mi, pe1.patev_event_time, pe2.patev_event_time))/count(*) as AvgMin
from risdb_rch08_stag..performed_procedure (index pp_serv_time_r_ndx), risdb_rch04_stag..patient_event pe1, risdb_rch04_stag..patient_event pe2
where pp_service_time_r between @Startdate and @Enddate and pp_asn_req_no = pe1.patev_asn_req_no and pp_asn_seq_no = pe1.patev_asn_seq_no and pp_status_v = 'CP' and pp_rep_id > 0 and pe1.patev_event_code = 'PB' and (pp_asn_req_no = pe2.patev_asn_req_no and pp_asn_seq_no = pe2.patev_asn_seq_no and pe2.patev_event_code = 'PL') and datediff (mi, pe1.patev_event_time, pe2.patev_event_time) > 0
I have a fairly complex SP with 3 tables the idea being to display a Region, Client and EventI want to show only the last event for each client I have replaced my event table with a View which returns the TOP 1 but all I get is the most recent of all records I want eg:Region 1, Client 1, Most recent event Region 1, Client 2, Most recent event Region 1, Client 3, Most recent event
if I create an index for a table with some records, do you think I can retrieve records in a giving range? for example, the 5th to 10th records?Possible? How can I do it?When we insert data at the table, would the index in sequential order? How would the index be created for new inserted records?I'm using SQL 2005 Express, not SQL 2000.
If I know the exact offset I can query easily enough using PropClass and the exact offset. But what if the offset is not included in the range for a given PropClass? How can I get a query to return the last valid record for a given PropClass from within a join?
For example, if my query contained PropClass = 1 and offset = 4, it should return the Amount of .50 from Record with ID 3
This is a query that I am trying to work on:
Code: SELECT v.District, v.PropClass, YearAquired, SUM(cost * cnt), SUM(v.Cost * v.Cnt * t.Amount), SUM(v.Tax), COUNT(*) FROM UPValue v INNER JOIN UPMaster m on m.Year = v.year and m.Account = v.account INNER JOIN UPTable T on t.PropClass = v.PropClass and t.Offset = v.Year - v.YearAquired WHERE v.Year = 2012 and LeaseType = 2 group by v.District, v.PropClass, YearAquired order by v.District, v.PropClass
Using <= will not work because that would return multiple records from UPTable when the offset is < the max offset.
I have a situation where an agent has number of activities for a certain date range. If an agent has multiple activities within certain date range, I would like BALANCE BEFORE from the first activity and BALANCE AFTER from the last activity. Here is my current SQL query that returns the following data:
DECLARE @BeginDate Datetime DECLARE @EndDate Datetime Set @BeginDate = '05-1-2015' Set @EndDate = '05-31-2015' SELECT a.AgentName, R.BALANCEBEFORE,
[Code] ....
AGENTNAME BALANCE BEFORE BALANCE AFTER DATE DOUGLAS 9738.75 9782.75 2015-05-11 DOUGLAS 9782.75 9804.75 2015-05-12 DOUGLAS 9804.75 9837.75 2015-05-13
In the sample data above, ideally I would like my query to return data as follow:
AGENTNAME BALANCE BEFORE BALANCE AFTER DOUGLAS 9738.75 (from first activity) 9837.75 (from last activity)
Not sure how I can write sql query to accomplish this.
I have a client who needs to copy an existing sale. The problem isthe Sale is made up of three tables: Sale, SaleEquipment, SaleParts.Each sale can have multiple pieces of equipment with correspondingparts, or parts without equipment. My problem in copying is when I goto copy the parts, how do I get the NEW sale equipment ids updatedcorrectly on their corresponding parts?I can provide more information if necessary.Thank you!!Maria
Hi I have a table with a user column and other columns. User column id the primary key.
I want to create a copy of the record where the user="user1" and insert that copy in the same table in a new created record. But I want the new record to have a value of "user2" in the user column instead of "user1" since it's a primary key
I have a UDF that takes my input and returns the next valid business day date. My valid date excludes weekends and holidays. It works perfect except for one issue. It doesn't check to see if today's date is a holiday. I pass a query to sql server like so " select dbo.getstartdate('01/ 10/2007',2)" It then moves ahead two business days and returns that date. Here is the current code. Hopefully someone can tell me how to do the holiday check on the current date. I really don't want to rewrite the whole script . Code--------------------------------------------------------- SET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS OFF GO --DROP FUNCTION GetStartDate --declare function receiving two parameters ---the date we start counting and the number of business days CREATE FUNCTION GetStartDate (@startdate datetime, @days int) RETURNS datetimeASBEGIN --declare a counter to keep track of how many days are passingdeclare @counter int /*Check your business rules. If 4 business days means you count starting tomorrow, set counter to 0. If you start counting today, set counter to 1*/set @counter = 1 --declare a variable to hold the ending datedeclare @enddate datetime --set the end date to the start date. we'll be -- incrementing it for each passing business dayset @enddate = @startdate /*Start your loop.While your counter (which was set to 1), is less than or equal to the number of business days increment your end date*/WHILE @counter <= @days BEGIN --for each day, we'll add one to the end dateset @enddate = DATEADD(dd, 1, @enddate) --If the day is between 2 and 6 (meaning it's a week --day and the day is not in the holiday table, we'll --increment the counter IF (DATEPART(dw, @enddate) between 2 and 6) AND (@enddate not in ( select HolidayDate from tFederalHoliday where [HolidayYear] = datepart(yyyy,@enddate) ) ) BEGIN set @counter = @counter + 1 END --end the while loopEND --return the end dateRETURN @enddate --end the functionEND GOSET QUOTED_IDENTIFIER OFF GOSET ANSI_NULLS ON GO ---------------------------------------------------------------------------------------------
I've a view in which one of the fields were DATEDIFF(day,contract date,received) AS AgeOfAccount. I changed it to DATEDIFF(day, m.received, CASE WHEN m.clidlp > m.clidlc THEN m.clidlp ELSE m.clidlc END) * - 1 AS AgeOfAccount. When I execute the view I'm getting an error. But the results are getting displayed properly. That's what's puzzling me. Could someone tell me what the error is.
The following errors were encountered while parsing the contents of the sql pane. Your entry cannot be converted to a valid date time value.
I have a search returning many 'car' records (regno, mileage, color, etc)
In a seperate table I have two columns: accessory and regno. This can have many rows for each regnumber.
Within the storedprocedure that returns the 'car' records I need to also return the relevant accessories for that car as one column.
I have written a function as such (with some help!):
ALTER Function getAccs(@regNo varChar(20)) RETURNS varChar AS BEGIN Declare @List varchar(1000) SELECT @List = COALESCE(@List + ', ', '') + accessory FROM frxrep2.dbo.usedaccessories WHERE regnumber = @regno return @List END
I was hoping that I could simply use this in the 'car' SELECT statement.
ie:
SELECT regNo, color, mileage, dob.getAccs(regno) as AccessoryList FROM tableBla etc
I'm not even sure if the function works - How can I test in SQL analyzer?
Hi everyone, I am tring to pass acomma delimited string to a function and this function is parsing the string so that I can see individual values so for example I am passing 1,2,3,4,5 as a parameter to my function and I am parsing this string so that I can write something like this Select * from tableA where userID in(1,2,3,4) It is working fine. Only problem is if the user passes word 'all' instead of 1,2,3,4 then I have to doSelect * from tableA My function looks like this. How can I modify this function if I pass 'all' as a paramater. Any help will be appreciated.CREATE FUNCTION [dbo].[ParseText2File] (@p_text varchar(4000), @p_Delimeter char(1)) RETURNS @results TABLE (id varchar(100)) AS BEGIN declare @i1 varchar(200) declare @i2 varchar(200) declare @tempResults Table (id varchar(100)) while len(@p_text) > 0 and charindex (@p_Delimeter, @p_text) <> 0 begin select @i1 = left(@p_text, charindex(@p_Delimeter, @p_text) - 1) insert @tempResults select @i1 select @p_text = right(@p_text, len(@p_text) - charindex(@p_Delimeter,@p_text)) end insert @tempResults select @p_text insert @results select * from @tempResults return END Thanks
I know that we cannot have User Defined Functions in SQL 7.0, but is there a work around. I am trying to standardize the date according to the time zone using a function and use it as part of a select statement.
I cannot believe that is not possible in SQL 7.0, can somebody tell me what is the work around, I am running against time. I really appreciate any help on this one.
I am a new user for SQL server. Coming from an oracle background, I find it very difficult to live without user defined functions. At the moment, I urgently need to have a function returning an custom-made ID string, so that it can be used in one of my stored procedures. I have heard the rumours that SQL server 7 does NOT support user defined functions, (which SQL 6.5 does). I would be really grateful if anyone can clarify this for me, and if possible, suggest a get-around approach.
all schedulled task on server failed for 18450 Process Exit Code 1. ...t Utility, Version 6.50.240 Copyright (C) Microsoft Corporation, 1995 - 1996 [Microsoft SQL-DMO] Error 18450: [SQL Server] Login failed- User: sqlexec Reason: Not defined as a valid user of a trusted SQL Server connection. Any information on how to solve it