Subquery Headache With Count And GroupBy
Nov 23, 2005
I'm trying to return an integer from the following table that returns
the number of unique cities:
tblEmployees
Name City
John Boston
Frank New York
Jim Omaha
Betty New York
The answer should be 3.
DECLARE @EmployeeCities int
SELECT @EmployeeCities = SELECT ... ???
How go I return one row/column into @EmployeeCities from a Count and a
GroupBy?
Headache already... Maybe it's too early...
View 3 Replies
ADVERTISEMENT
Oct 19, 2004
I have a table that has attendance for programs. What I need to get is the number of days each month that any program had an entry for. What I'm trying to do is ensure that an active program had all entries for that particular month.
I can do this query and subquery in Access but not in sql. Here's the Access queries:
1)SELECT Cen_DailyReport.PgmID, DatePart("m",[date]) AS Mo, DatePart("d",[date]) AS Dy
FROM Cen_DailyReport
WHERE (((DatePart("yyyy",[Date]))=2004))
GROUP BY Cen_DailyReport.PgmID, DatePart("m",[date]), DatePart("d",[date])
HAVING (((Cen_DailyReport.PgmID)="dyad"));
Then to get the actual day count per month, the next query is:
2) SELECT Query11a.PgmID, Query11a.Mo, Count(Query11a.Dy) AS CountOfDy
FROM Query11a
GROUP BY Query11a.PgmID, Query11a.Mo;
and this query aggregates the data from the 1st query. I'm wanting to do this in SQL.
In the long run, I want to take that count in the query and compare it with the actual number of days in a month to see if any entries are missing (like a program not being entered at all on any given day that they should have had entries for)
Any help would be appreciated.
View 1 Replies
View Related
Apr 18, 2008
I am attempting to do something like this...
select * from applebucket ab where 2 = (select count(id) from apples ap where ap.applebucket_id = ab.id)
SSCE 3.1 throws the following
There was an error parsing the query. [ Token line number = x,Token line offset = y,Token in error = SELECT ]
Any help would be greatly appreciated!
View 3 Replies
View Related
Oct 28, 2006
I have 2 tables, Jobs and Categories.Each job belongs to a category. At present, I am returning all categories as follows:SELECT categoryID, categoryName FROM TCCI_CategoriesWhat I'm trying to do, is also return the number of jobs assigned to each category, so in my web page display, it would show something like this:Engineering(5)Mechanical(10) etc.My db currently has 5 categories, with only one job assigned to a category. I tried the following sub-query, but instead of returning all the categories with their job counts, it just returns the category that has a job assigned to it:SELECT c.categoryID, c.categoryName, COUNT(j.jobID)FROM TCCI_Categories c, (SELECT jobID, categoryID FROM TCCI_Jobs) jWHERE j.categoryID = c.categoryIDGROUP BY c.categoryID, c.categoryName, j.jobIDThis is the output when I run the query:categoryID categoryName Column1 ---------------- ---------------------- ------------------------------32 Engineering 1 How would I fix this?
View 2 Replies
View Related
Sep 2, 2015
updating the # of Payer from below query to match with the # of rows for each payer record. See the Current and desired results below. The query is currently counting the # of rows for all payers together and updating 3 as # of payers. I need it to count # of rows for each payer like shown inDesired result below. It should be showing 1 for first payer and 2 for 2nd & 3rd based on # of times each payer is repeated..
SELECT b.FILING_IND, b.PYR_CD, b. PAYER_ID, b. PAYER_NAME,a.CLAIM_ICN,
(Select Count(*) From MMITCGTD.MMIT_CLAIM a, MMITCGTD.MMIT_TPL b , MMITCGTD.MMIT_ATTACHMENT_LINK c where a.CLAIM_ICN_NU =
c.CLAIM_ICN and b.TPL_TS = c.TPL_TS and a.CLAIM_TYPE_CD = 'X'
[Code] ....
Current Result
FILING_IND
PYR_CD
PAYER_ID
PAYER_NAME
CLAIM_ICN
#_OF_PAYER
[code]....
View 4 Replies
View Related
Apr 26, 2008
hello friends.. I am newbie for sql server...I having a problem when executing this procedure .... ALTER PROCEDURE [dbo].[spgetvalues] @Uid intASBEGIN SET NOCOUNT ON; select DATEPART(year, c.fy)as fy, (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1% JRF' ) as survivorship, (select contribeamount from wh_contribute where and contribename like 'Gross Earnings' and ) as ytdgross, (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1.5% JRP') as totalcontrib, from wh_contribute c where c.uid=@Uid Order by fy Asc .....what is the wrong here?? " Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."please reply asap...
View 1 Replies
View Related
Jul 20, 2005
I am getting 2 resultsets depending on conditon, In the secondconditon i am getting the above error could anyone help me..........CREATE proc sp_count_AllNewsPapers@CustomerId intasdeclare @NewsId intset @NewsId = (select NewsDelId from NewsDelivery whereCustomerId=@CustomerId )if not exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count( NewsPapersId) from NewsPapersendif exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count(NewsDelId) from NewsDelivery whereCustomerid=@CustomeridendGO
View 3 Replies
View Related
Mar 6, 2008
I am getting an error as
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
while running the following query.
SELECT DISTINCT EmployeeDetails.FirstName+' '+EmployeeDetails.LastName AS EmpName,
LUP_FIX_DeptDetails.DeptName AS CurrentDepartment,
LUP_FIX_DesigDetails.DesigName AS CurrentDesignation,
LUP_FIX_ProjectDetails.ProjectName AS CurrentProject,
ManagerName=(SELECT E.FirstName+' '+E.LastName
FROM EmployeeDetails E
INNER JOIN LUP_EmpProject
ON E.Empid=LUP_EmpProject.Empid
INNER JOIN LUP_FIX_ProjectDetails
ON LUP_EmpProject.Projectid = LUP_FIX_ProjectDetails.Projectid
WHERE LUP_FIX_ProjectDetails.Managerid = E.Empid)
FROM EmployeeDetails
INNER JOIN LUP_EmpDepartment
ON EmployeeDetails.Empid=LUP_EmpDepartment.Empid
INNER JOIN LUP_FIX_DeptDetails
ON LUP_EmpDepartment.Deptid=LUP_FIX_DeptDetails.Deptid
AND LUP_EmpDepartment.Date=(SELECT TOP 1 LUP_EmpDepartment.Date
FROM LUP_EmpDepartment
WHERE EmployeeDetails.Empid=LUP_EmpDepartment.Empid
ORDER BY LUP_EmpDepartment.Date DESC)
INNER JOIN LUP_EmpDesignation
ON EmployeeDetails.Empid=LUP_EmpDesignation.Empid
INNER JOIN LUP_FIX_DesigDetails
ON LUP_EmpDesignation.Desigid=LUP_FIX_DesigDetails.Desigid
AND LUP_EmpDesignation.Date=(SELECT TOP 1 LUP_EmpDesignation.Date
FROM LUP_EmpDesignation
WHERE EmployeeDetails.Empid=LUP_EmpDesignation.Empid
ORDER BY LUP_EmpDesignation.Date DESC)
INNER JOIN LUP_EmpProject
ON EmployeeDetails.Empid=LUP_EmpProject.Empid
AND LUP_EmpProject.StartDate=(SELECT TOP 1 LUP_EmpProject.StartDate
FROM LUP_EmpProject
WHERE EmployeeDetails.Empid=LUP_EmpProject.Empid
ORDER BY LUP_EmpProject.StartDate DESC)
INNER JOIN LUP_FIX_ProjectDetails
ON LUP_EmpProject.Projectid=LUP_FIX_ProjectDetails.Projectid
WHERE EmployeeDetails.Empid=1
PLEASE HELP.................
View 1 Replies
View Related
May 14, 2008
Hi,
I've running the below query for months ans suddenly today started getting the following error :"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
Any ideas as to why??
SELECT t0.DocNum, t0.Status, t0.ItemCode, t0.Warehouse, t0.OriginNum, t0.U_SOLineNo, ORDR.NumAtCard, ORDR.CardCode, OITM_1.U_Cultivar,
RDR1.U_Variety,
(SELECT OITM.U_Variety
FROM OWOR INNER JOIN
WOR1 ON OWOR.DocEntry = WOR1.DocEntry INNER JOIN
OITM INNER JOIN
OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod ON WOR1.ItemCode = OITM.ItemCode
WHERE (OITB.ItmsGrpNam = 'Basic Fruit') AND (OWOR.DocNum = t0.DocNum)) AS Expr1, OITM_1.U_Organisation, OITM_1.U_Commodity,
OITM_1.U_Pack, OITM_1.U_Grade, RDR1.U_SizeCount, OITM_1.U_InvCode, OITM_1.U_Brand, OITM_1.U_PalleBase, OITM_1.U_Crt_Pallet,
OITM_1.U_LabelType, RDR1.U_DEPOT, OITM_1.U_PLU, RDR1.U_Trgt_Mrkt, RDR1.U_Wrap_Type, ORDR.U_SCCode
FROM OWOR AS t0 INNER JOIN
ORDR ON t0.OriginNum = ORDR.DocNum INNER JOIN
RDR1 ON ORDR.DocEntry = RDR1.DocEntry AND t0.U_SOLineNo - 1 = RDR1.LineNum INNER JOIN
OITM AS OITM_1 ON t0.ItemCode = OITM_1.ItemCode
WHERE (t0.Status <> 'L')
Thanks
Jacquues
View 4 Replies
View Related
Apr 8, 2008
i have one query:
SELECT MAX(salesid) AS salesid, max(salestitle) as salestitle
FROM saleshistory s where list = 'sales'
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, salesdate), 0)
order by salestitle
i m getting more than 1000 rows.. in output
some of them are :
salesid salestitle
---------------------------------
11871/20/2005 9:45:54 AM
821622K8_KTBcalendar_pre1 9/19/2007 10:46:02 AM
824962K8_KTBcalendar_pre1 9/20/2007 3:29:44 PM
918572K8_KTBcalender_inst 10/16/2007 2:47:31 PM
175660AmerHeartMo_2008 2/22/2008 1:05:24 PM
179614AmerHeartMo_2008 2/26/2008 4:54:18 PM
2554American_Heart_Month_Feb2005
25335Cholesterol_Educ_Mo_2006_Rem_test
25186Cholesterol_Educ_Mo_2006_Rem_test
25282Cholesterol_Educ_Mo_2006_Rem_test
i want (desired)output like: -
11871/20/2005 9:45:54 AM
824962K8_KTBcalendar_pre1 9/20/2007 3:29:44 PM
918572K8_KTBcalender_inst 10/16/2007 2:47:31 PM
179614AmerHeartMo_2008 2/26/2008 4:54:18 PM
2554American_Heart_Month_Feb2005
25335Cholesterol_Educ_Mo_2006_Rem_test
i want max(salesid) among that same salestitle
when i m doing like:
SELECT MAX(salesid) AS salesid, max(salestitle) as salestitle
FROM saleshistory s where list = 'sales'
GROUP BY substring([salestitle],1,charindex(' ',[salestitle])-1)
i m getting an error
Msg 536, Level 16, State 3, Line 1
Invalid length parameter passed to the substring function.
(0 row(s) affected)
can anybody help me to get correct output.
thanks.
View 9 Replies
View Related
Feb 10, 2007
Respected Friends,
kindly solve my query.
Table Structrue:
Table Name : Custom_Table_SPPR_Master
Fields :
Sno int pk
SPPR_No int pk
Revison_No int pk
rev_Date date
prop_amt decimal
claim_amt decimal
avail_amt decimal
Status int
Data
Sno SPPR_No Revison_No rev_Date prop_amtclaim_amtavail_amtStatus
1 2000 0 2006-10-01 00:00:00.000 1000 600 400 2
2 2000 1 2006-10-01 00:00:00.000 1100 600 500 2
3 2000 2 2006-10-01 00:00:00.000 1400 600 800 2
4 2000 3 2006-10-01 00:00:00.000 1500 900 600 2
5 2001 0 2006-10-01 00:00:00.000 1000 200 800 2
6 2001 1 2006-10-01 00:00:00.000 1200 600 600 2
7 2002 0 2006-10-01 00:00:00.000 1000 600 400 2
8 2002 1 2006-10-01 00:00:00.000 1100 600 500 2
9 2003 0 2006-10-01 00:00:00.000 1000 600 400 2
I want the record where max of the revision no is seen for each sppr
that is the result should the rows of sno: 4,6,8,9
i tried the following but in vein
select max(revision_no) ,sppr_no from Custom_Table_SPPR_Master group by sppr_no
-- in this i am getting records, but i want * datas
select distinct(sppr_no) from Custom_Table_SPPR_Master where revision_no in(select max(revision_no) from Custom_Table_SPPR_Master group by revision_no) group by sppr_no
select sppr_no,count(revision_no) from Custom_Table_SPPR_Master where revision_no in(select max(revision_no) from Custom_Table_SPPR_Master group by revision_no)
group by sppr_no,revision_no
Kindly let me the answers . thanks in advance.
View 2 Replies
View Related
Apr 23, 2007
Hi,
I need help in creating a query using MAX and group by.
The input SQL table ClientInfo contains data like the following:
Client Div MaxDt
00003 00 19820501
00003 00 19830208
00003 00 19850801
00003 00 20040811
00003 50 19850101
00003 50 20040811
00003 99 19870131
I need the output to have the max date for every division of every client and output should be as follows:
Client Div MaxDt
00003 00 20040811
00003 50 20040811
00003 99 19870131
Thanks,
View 7 Replies
View Related
Mar 17, 2008
Hi.I've wrote this query:
SELECT TOP 10 COUNT(*) AS ItemsSold, ProductName, order_details_product_id, SUM(order_details_price) AS order_details_price
FROM tbl_Detail_Order_Product
WHERE (OrderStatus NOT IN (14, 15))
GROUP BY order_details_product_id, ProductName, order_details_price
ORDER BY ItemsSold DESC
which works fine and have these results:
Purchased Returned Sold Part Number
$ 598.29 37 16684
$ 200.29 33 16654
$ 300.29 25 16184
.
.
.
my problem is I want to show the returned column wich is:
WHERE (OrderStatus IN (14, 15))
I dont know how can I do that.
I tried to write another query but it didnt worked correctly.
plz help me.
thanks
View 1 Replies
View Related
May 6, 2004
hi
I have MSSQL query that performs multiple UNION ,but I would like to perform a GROUPBY on the whole result set.
How Can i do this?
plz help...
bono
View 4 Replies
View Related
Jun 15, 2008
alter PROCEDURE [dbo].[spsite]
@fromdate datetime,
@todate datetime
AS
BEGIN
select site as sitecode,
count(id) as t from an where mydate >=@fromdate and mydate<=@todate,
count(id) as p from an where p=1 and mydatestage1 >=@fromdate and mydatestage1<=@todate
group by site
what am i doing wrong?
I get incorrect syntax near ,
View 7 Replies
View Related
Aug 9, 2006
Fred writes "How to retrieve rows for which sum of the qty field equals to a specified number - let's consider a basic table as with 3 fields : item (pk), qty, orderid (fk) :
item qty orderid
**** *** *******
itemA 1 ord-18/07/06
itemB 2 ord-01/01/05
itemC 2 ord-18/07/06
itemD 3 ord-18/07/06
itemE 1 ord-18/07/06
I want to know belong ord-18/07/06's items, which ones to pick up in order to reach a total qty of 5. Answer is itemC (2) + itemD (3). I tried with various combinations of SUM,MAX,HAVING.. Can't make it works. Help appreciated. Rgds."
View 1 Replies
View Related
Feb 19, 2008
Hi,
I have a problem regarding this i have this statement where in i can count the number of data and display what category is that.... my problem is how can i sum itHere's the Statement
SELECT Count([PullOut].[SOType]) as Count, [SODescription].[SODescription]
FROM PullOut INNER JOIN SODescription ON [PullOut].[SOType]=[SODescription].[SOType]
WHERE PullOut.Area in ('Rizal','Cavite')
GROUP BY [SODescription].[SODescription];
Output:
1 Category1
5 Category2
2 Category3
....i want only to display the sum of this....
8 Total
Regards
View 5 Replies
View Related
Mar 31, 2008
in my sql query,when it run then it displays records as follows
dt_id daily_type dates emp_mgmt_id emp_name etc--------
48 Electrical 03/14/2008 22 abc
----------
49 Mechanical 03/14/2008 35 xyz
-------------
48 Electrical 03/14/2008 22 abc
----------
49 Mechanical 03/14/2008 35 xyz
-------------
i want to display records only once like as follows
dt_id daily_type dates emp_mgmt_id emp_name etc--------
48 Electrical 03/14/2008 22 abc
----------
49 Mechanical 03/14/2008 35 xyz
-------------
if i use group by on some fields then it gives error as follows
Column 'Daily_Time_Entry.daily_type' is invalid in the select list because it is
not contained in either an aggregate function or the GROUP BY clause.
so how can i design query so records display only once not repeated,or is any
alternative,to solve this .
my sql query as follows
SELECT dl.dt_id, dl.daily_type, convert(char,dl.dt_date,101) as
dates,dl.emp_mgmt_id,
emp.emp_name,emp.employee_id,dl.project_type,dl.project_id,
dl.cec_job_id,
cec.cecjobname,dl.time_st,dl.time_ot,dl.time_dt,op.other_proj_id,
op.customer_name,op.project_name,op.owner_rep_phone_num1,dl.work_desc,
m.material_id,m.material_type,m.material_date, m.project_type
,m.project_id,
m.qty,m.description,m.material_unit_price,m.material_markup,
m.material_subtotal,
m.cec_job_id,m.location
FROM material m left outer join
Other_Project op on m.project_id=op.other_proj_id left outer join
Daily_Time_Entry dl on
dl.project_id =op.other_proj_id inner join Employee_Mgmt emp
on emp.emp_mgmt_id = dl.emp_mgmt_id inner join CEC_Job cec
ON dl.cec_job_id = cec.cec_job_id
where (dl.dt_date='3/14/2008'and m.material_date='3/14/2008') and
(dl.project_type='Other Project' and m.project_type = 'Other Project')
and (dl.cec_job_id=m.cec_job_id) and (dl.daily_type='Electrical') and
(dl.project_id='18')
uday
View 3 Replies
View Related
Mar 9, 2005
Hi All,
I have a table called Prizes. Here's how it looks in design view with some value placed inside for Illustration purposes.
PrizeID 1, 2, 3, 4, 5
PromotionID 1, 1, 1, 2, 1
PrizeName 10 Cash, 5 cash, 10 cash, 15 cash, 20 cash
My challenge is that I need to write a stored procedure for example, that will find the PrizeID associated with the 4th count of the PromotionID that equals 1 . So in this example, counting to the 4th PromotionID that equalls 1 give us a PrizeID of 5.
I hope I've made myself clear! Can anyone write out a mini SP on how to do this.
Many many thanks in advance,
Brad
View 2 Replies
View Related
Mar 13, 1999
I need to get this statement to run.
Declare @MiD datetime
-- The ATime is a datetime field in the table
-- @OrderBy is an input Parameter also, as is @MiD
SELECT @Statement = 'SELECT tblAudit.* FROM tblAudit WHERE ATime >= ' + @MiD + ' ORDER BY ' + @OrderBy
EXECUTE(@Statement)
@Statement then contains:
SELECT tblAudit.* FROM tblAudit WHERE ATime >= Mar 10 1999 ORDER BY Access_ID
I need the quotes around the Mar 10 1999.
Thanks for the help
View 2 Replies
View Related
Jun 24, 2004
Hallo
I am interrogating the structure of SQL Server database looking for the occurence of a particular phrase in the object names/definitions. This is in preparation for decommission/replacement...
When I run the script below in SQL Query Analyzer it returns about 200 results, but when I run the same query in my Access VBA code it returns much less!
SQL Script:
SELECT
so.ID,
so.name,
so.type,
CHARINDEX('insita',so.name) AS PosInObjName,
CASE WHEN CHARINDEX('insita',so.name) > 0 THEN 1 ELSE 0 END AS FoundInObjName,
CHARINDEX('insita',sc.text) AS PosInObjDef,
CASE WHEN CHARINDEX('insita',sc.text) > 0 THEN 1 ELSE 0 END AS FoundInObjDef
FROM
sysobjects so INNER JOIN syscomments sc on so.id = sc.id
ORDER BY [name]
VB Code:
Sub InterrogateDatabaseStructure(sServer As String, sDB As String, sSearch4 As String)
On Error GoTo err_IDS
Dim oCnn As ADODB.Connection
Dim oCmd As ADODB.Command
Dim oRs As ADODB.Recordset
Dim sSQL As String
Set oCnn = New ADODB.Connection
oCnn.ConnectionString = "driver={SQL Server};server=" & sServer & ";uid=;pwd=;database=" & sDB & ";dsn=;"
oCnn.Open
CurrentDb.Execute "DELETE * FROM PhraseSearchResults"
CurrentDb.Execute "DELETE * FROM PhraseInObjName"
Set oCmd = New Command
oCmd.ActiveConnection = oCnn
oCmd.CommandType = adCmdText
sSQL = "SELECT so.ID, so.name, so.type, "
sSQL = sSQL & "CASE WHEN CHARINDEX('" & sSearch4 & "',so.name) > 0 THEN 1 ELSE 0 END AS FoundInObjName,"
sSQL = sSQL & "CHARINDEX('" & sSearch4 & "',so.name) AS PosInObjName, "
sSQL = sSQL & "CASE WHEN CHARINDEX('" & sSearch4 & "',sc.text) > 0 THEN 1 ELSE 0 END AS FoundInObjDef, "
sSQL = sSQL & "CHARINDEX('" & sSearch4 & "',sc.text) AS PosInObjDef "
sSQL = sSQL & "FROM " & sDB & ".dbo.sysobjects so INNER JOIN syscomments sc on so.id = sc.id"
oCmd.CommandText = sSQL
Set oRs = oCmd.Execute()
With oRs
If Not .EOF And Not .BOF Then
.MoveFirst
Do Until .EOF
sSQL = "INSERT INTO PhraseSearchResults VALUES('"
sSQL = sSQL & .Fields(0) & "','" & .Fields(1) & "','" & .Fields(2) & "',"
sSQL = sSQL & .Fields(3) & "," & .Fields(4) & ")"
CurrentDb.Execute sSQL
.MoveNext
Loop
End If
End With
Set oCmd = Nothing
Set oCnn = Nothing
Exit Sub
err_IDS:
MsgBox "Error: " & Err.Description & vbCr & "Error Code: " & Err.Number
Screen.MousePointer = 0
End Sub
Can anyone please advise what I am doing wrong? Thanks.
View 1 Replies
View Related
Dec 5, 2005
Guys
I have a table 1 row, a start and end date of a period
create table xperiod(startdate datetime , enddate datetime)
insert xperiod (startdate , enddate)
values ('2004-04-01 00:00:00.000' , 2012-03-31 00:00:00.000)
I'm trying to retrieve a batch of 'smaller' periods from this where the relevant period is a number (of months) passed as a parameter (only ever 1, 3 or 6)
for example, if the parameter is 1 I will obtain the following rows each being a 1 month period starting at the xperiod.startdate value up to an end date of the xperiod.enddate value
startperiod endperiod
'2004-04-01 00:00:00.000' '2004-04-30 00:00:00.000'
'2004-05-01 00:00:00.000' '2004-05-31 00:00:00.000'
'2004-05-01 00:00:00.000' '2004-05-31 00:00:00.000'
and so on to
'2012-03-01 00:00:00.000' '2012-03-31 00:00:00.000'
if the parameter is 3 I will obtain the following rows each being a 3 month period starting at the xperiod.startdate value up to an end date of the xperiod.enddate value
startperiod endperiod
'2004-04-01 00:00:00.000' '2004-06-30 00:00:00.000'
'2004-07-01 00:00:00.000' '2004-09-30 00:00:00.000'
'2004-10-01 00:00:00.000' '2004-12-31 00:00:00.000'
and so on to
'2012-01-01 00:00:00.000' '2012-03-31 00:00:00.000'
Hope this makes sense !
I think I'll be ok on the logic for the while loop but my main problem is getting the endperiod value based on the startperiodvalue
Thx in advance
View 2 Replies
View Related
Aug 10, 2006
Hello - hope this is in the right group:We have just started with linked servers and have successfully createda view on SQL Server linked to a Progress database. I can query thisview happily in Query Analyzer.I have created an ASP.NET application to display this view in adatagrid but I get the following error:System.Data.SqlClient.SqlException: OLE DB provider 'MSDASQL' reportedan error. at System.Data.SqlClient.SqlConnection.OnError(SqlExc eptionexception, Boolean breakConnection) atSystem.Data.SqlClient.SqlInternalConnection.OnErro r(SqlExceptionexception, Boolean breakConnection) atSystem.Data.SqlClient.TdsParser.ThrowExceptionAndW arning(TdsParserStateObjectstateObj) at System.Data.SqlClient.TdsParser.Run(RunBehaviorrunBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)at System.Data.SqlClient.SqlDataReader.ConsumeMetaDat a() atSystem.Data.SqlClient.SqlDataReader.get_MetaData() atSystem.Data.SqlClient.SqlCommand.FinishExecuteRead er(SqlDataReader ds,RunBehavior runBehavior, String resetOptionsString) atSystem.Data.SqlClient.SqlCommand.RunExecuteReaderT ds(CommandBehaviorcmdBehavior, RunBehavior runBehavior, Boolean returnStream, Booleanasync) atSystem.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehaviorcmdBehavior, RunBehavior runBehavior, Boolean returnStream, Stringmethod, DbAsyncResult result) atSystem.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehaviorcmdBehavior, RunBehavior runBehavior, Boolean returnStream, Stringmethod) atSystem.Data.SqlClient.SqlCommand.ExecuteReader(Com mandBehaviorbehavior, String method) atSystem.Data.SqlClient.SqlCommand.ExecuteDbDataRead er(CommandBehaviorbehavior) atSystem.Data.Common.DbCommand.System.Data.IDbComman d.ExecuteReader(CommandBehaviorbehavior) at System.Data.Common.DbDataAdapter.FillInternal(Data Setdataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords,String srcTable, IDbCommand command, CommandBehavior behavior) atSystem.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32startRecord, Int32 maxRecords, String srcTable, IDbCommand command,CommandBehavior behavior) atSystem.Data.Common.DbDataAdapter.Fill(DataSet dataSet) at...The code in my ASP.NET application looks fine and works on non-linkedviews on the same server. Do I need to add a command or change asetting on SQL Server?
View 2 Replies
View Related
May 3, 2006
Hi Folks,
I'm still using the the SQL Server 2005 June CTP to develop. I'm working for a client that intends to upgrade, but has not done so yet. We believed that we had 365 days from the date of installation before it would expire (late July). But Visual Studio 2005 Beta 2 just expired, which is used by SQL Server Business Intelligence Development Studio, so now we can no longer develop SSIS packages or Reporting Services reports.
What can I do?
I thought that maybe installing Visual Studio 2005 express might work, but when I went there, it seems that it is split up into modules (e.g. Visual Basic 2005 express, Visual C++ express, etc...). I don't know if just one of these would be sufficient and if so, which one. Even if it would, it says I'll need to completely remove the SQL Server 2005 beta, as well as the Visual Studio 2005 beta, and I think the .net framework.
My contract is up at the end of June, and it was understood that the client was going to take care of the upgrade. Is there a quick fix here? What can I do with minimal effort? (I don't really have time to wait for the client to get the upgrade approved and done. I know, sniff, sniff! lol.)
View 1 Replies
View Related
Jul 23, 2005
I have a table (tblA) that records the RecordID, UserID andLastViewedDate (DateTime) of each record opened in tblB where RecordIDis the PK in tblB. I want to construct a query that groups all recordsin tblA by RecordID, filters by UserID and keeps only the most recent25 RecordIDs and deletes the rest.This gets me a recordset of all RecordIDs filtered by UserID in tblAbut I can't figure out how to sort it by LastViewedDate DESC and toeliminate those not in the Top25:SELECT RecordIDFROM dbo.tblAWHERE (UserID = 1234)GROUP BY RecordIDAny help is appreciated!lq
View 4 Replies
View Related
Nov 16, 2007
Hi!
I have a data (txt) file which has the following structure
M_ID1:
CID11,Date11
CID12,Date12
M_ID2:
CID,Date21
CID,Date22
My problem now is it, to get that into a table (MID,CID,DATE) as the text file "groups" CID and DATE by MID and
I have no idea how to read the file and transform it.
Well, perhaps somebody out there has an idea!
Thanks in advance!
alx
View 4 Replies
View Related
Jul 19, 2007
Hi guys,
A have a problem that I need understand.... I have 2 server with the same configuration...
SERVER01:
-----------------------------------------------------
Microsoft SQL Server 2000 - 8.00.2191 (Intel IA-64)
Mar 27 2006 11:51:52
Copyright (c) 1988-2003 Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
sp_dboption 'BB_XXXXX'
The following options are set:
-----------------------------------
trunc. log on chkpt.
auto create statistics
auto update statistics
********************************
SERVER02:
-----------------------------------------------------
Microsoft SQL Server 2000 - 8.00.2191 (Intel IA-64)
Mar 27 2006 11:51:52
Copyright (c) 1988-2003 Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
sp_dboption 'BB_XXXXX'
The following options are set:
-----------------------------------
trunc. log on chkpt.
auto create statistics
auto update statistics
OK, the problem is that if a run the below query in server01, i get error 512:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
But, if run the same query in the server02, the query work fine -.
I know that I can use IN, EXISTS, TOP, etc ... but I need understand this behavior.
Any idea WHY?
SELECT dbo.opf_saldo_ctb_opc_flx.dt_saldo,
dbo.opf_saldo_ctb_opc_flx.cd_indice_opf,
dbo.opf_saldo_ctb_opc_flx.cd_classificacao,
dbo.opf_movimento_operacao.ds_tipo_transacao ds_tipo_transacao_movimento ,
dbo.opf_header_operacao.ds_tipo_transacao ds_tipo_transacao_header,
'SD' ds_status_operacao,
dbo.opf_header_operacao.ds_tipo_opcao ,
dbo.opf_header_operacao.id_empresa,
dbo.opf_saldo_ctb_opc_flx.ic_empresa_cliente,
0 vl_entrada_compra_ctro ,0 vl_entrada_compra_premio,
0 vl_entrada_venda_ctro , 0 vl_entrada_venda_premio,
0 vl_saida_compra_ctro, 0 vl_saida_compra_premio,
0 vl_saida_venda_ctro, 0 vl_saida_venda_premio,
0 vl_lucro , 0 vl_prejuizo, 0 vl_naoexec_contrato,
0 vl_naoexec_premio,
sum(dbo.opf_saldo_ctb_opc_flx.vl_aprop_ganho) vl_aprop_ganho,
sum(dbo.opf_saldo_ctb_opc_flx.vl_aprop_perda) vl_aprop_perda,
sum(dbo.opf_saldo_ctb_opc_flx.vl_rever_ganho) vl_rever_ganho,
sum(dbo.opf_saldo_ctb_opc_flx.vl_rever_perda) vl_rever_perda,
sum(dbo.opf_saldo_ctb_opc_flx.vl_irrf) vl_irrf
FROM dbo.opf_saldo_ctb_opc_flx,
dbo.opf_header_operacao ,
dbo.opf_movimento_operacao
WHERE dbo.opf_saldo_ctb_opc_flx.dt_saldo = '6-29-2007 0:0:0.000'
and ( dbo.opf_header_operacao.no_contrato = dbo.opf_saldo_ctb_opc_flx.no_contrato )
and ( dbo.opf_header_operacao.no_contrato = dbo.opf_movimento_operacao.no_contrato )
and ( dbo.opf_movimento_operacao.dt_pregao = (select (o.dt_pregao) from dbo.opf_movimento_operacao o
where o.no_contrato = dbo.opf_movimento_operacao.no_contrato and o.dt_pregao <='6-28-2007 0:0:0.000' ) )
and (dbo.opf_saldo_ctb_opc_flx.ic_tipo_saldo = 'S')
group by dbo.opf_saldo_ctb_opc_flx.dt_saldo,
dbo.opf_saldo_ctb_opc_flx.cd_indice_opf,
dbo.opf_saldo_ctb_opc_flx.cd_classificacao,
dbo.opf_movimento_operacao.ds_tipo_transacao,
dbo.opf_header_operacao.ds_tipo_transacao ,
ds_status_operacao,
dbo.opf_header_operacao.ds_tipo_opcao ,
dbo.opf_header_operacao.id_empresa,
dbo.opf_saldo_ctb_opc_flx.ic_empresa_cliente
Thanks
Nilton Pinheiro
View 9 Replies
View Related
Dec 10, 2005
This is more of an SQL server question than ASP.net.
A stored proc named MyStoredProc is created by admin account (sa) thus the owner of that proce is dbo.
When I log in to the database (Query Analyzer) as another login say User1, I can not use that stored proc since it was owned by sa. I get an error 'Invalid Object Name' or Object does not exist.
If I use the proper name qualifier like dbo.MyStoredProc, It works in the Query analyzser.
The problem I am facing is - My stored procedures, Views, Tables were created by sa on the development machine. Now its time for deployment. On the deployment machine, I am not the sa. I just belong to the db_Owner role. I have to log in as User1 and not as sa. In my c# code I have called the stored procedure as MyStoredProc. I get an error 'MyStoredProc does not exist' since I am loging in as User1 and not sa. In order to use the code, I have to change the ownership to this (and all other objects) to User1.
Is that the only way out or I am doing something wrong/missing someting? Your coments/opinions/suggestions welcome.
View 1 Replies
View Related
Sep 28, 2005
I have two tables, both with phone numbers and call times.
one is for incoming calls, one for outgoing calls.
I need to find all phone numbers from the incoming calls table where the number of calls exceeds 100 within the last 30 days, where the last call was within the last 15 mins, and where the number does Not exist in the outgoing call table within the last 30 days.
so far I have this...
(call record is the incoming, callout is the outgoin)
I believe this is giving me all records in the call record table that are within the last month, and not in the outgoing call table OR have not ben called within the last month..
SELECT cr.cli,min(cr.starttime)as "first call",max(cr.starttime)as "last call",count(cr.cli) as "number of calls"
FROM callrecord cr
LEFT JOIN callout co
ON cr.cli = co.cli
where (co.cli is null or datediff(dy,co.calltime,getdate())>30 )
and datediff(dy,cr.starttime,getdate())>30
group by cr.cli
order by cr.cli
i need to add in the 15 minute call check, and also only return those with a count of > 100
can anyone assist? i'm getting a headache :D
tia
a
View 4 Replies
View Related
Oct 12, 2006
I am using SQL server 2000.
While using query analyzer I am facing problem.
If a query has group by clause and if that query is not fetching any record (i.e. query is returning nothing), then in this situation, I want zero to be displayed where datatype of field is integer and "-" if datatype of field is varchar.
Please give me solution as soon as possible, a kind request.
Facing problem for the below mentioned query:-
select IsD.ItemCode,
case
when sum(IsD.IssuedQty) is null then 0
else sum(IsD.IssuedQty)
end as IssuedToday
from Inv_IssueMaster IsM, Inv_IssueDetail IsD
where IsM.IssueNo=IsD.IssueNo
group by IsD.ItemCode
In the above mentioned query, datatype of IssuedQty is int and for ItemCode it's varchar.
View 14 Replies
View Related
Jan 4, 2006
Hello,
Harry Half wit here!!
I know that snapshot replication is the simplest form of syncing with SQL server and I can't even figure that out today!!.
I keep getting myself confused as to who should be configured to be a publisher, distibutor or subscriber etc etc.
My scenario is simple:
1 server creating a daily snapshot of a table and then 1 remote laptop (msde) pulls the snapshot into it's own database.
Heres what i did so far;
I configured the server to be a publisher and distributor (is that right?) and didn't set up any subscribers because i want to do that from my remote.
From the remote I did nothing but go into EM tools"create new pull subscription" but I cannot see the publication on the server.
SHould I set my remote to be a distributor to do this?
any help very much appreciated!!
View 1 Replies
View Related
Oct 12, 2006
hi all,
i am having a hell of a time trying to understand how im supposed to use the reporting services integrated with sql server 2005 express - advanced. i have searched high and low throughout vb 2005 express for the relevant controls, and i have searched the management studio trying to find the relevant information. there is no reporting server anywhere that i can see. i simply installed the sqlexpr_adv.exe and assumed that all the relevant features would be automatically installed. i cant find them anywhere (also something about a business intelligence thing? also missing). i would be extremely grateful if somebody could help me
regards
adam
View 2 Replies
View Related
Jan 15, 2015
I have a query to get data group by High, Medium and Low so only three rows will be returned.
select
sum(case .... ) then 1 else 0 end) as [Column1],
sum(case .... ) then 1 else 0 end) as [Column2],
sum(case .... ) then 1 else 0 end) as [Column3]
from sometable
Group by High, Medium, Low
I want to manually add High, Medium and Low to each row's first column. the final result should look like:
Column1 Column2 Column3
High 123 123 123
Medium 123 123 123
Low 123 123 123
How can I do it?
View 2 Replies
View Related