Query Not Showing All The Records?!

Feb 8, 2008

I want to have all the ethnicities from the Ethnicgroup table to be displayed in a particular area which is in where clause as
aggcourseid

The problem is that even when I have a left join on the EthnicGroup table it will not return all the ethnicities but will only return those who were existing in that particular aggcourseid.

i.e. If there is no African student in E2, it will not show up in the result whereas I want to display all the ethnicities and if there is no record for aggcourseid, it should show up as 0/NULL for that ethnicity.

I have tried all sorts of joins but the problem is whenever I put in the aggcourseid in where clause, it wont bring all the records


declare @mpid char (13)


set @mpid = '011142'

create table #temp_et (
[Year]int NOT NULL,
[Ethnicity] varchar(20),
[Starts]float(4),
[Success]float(4),
[Retention]float(4),
[Achievement]float(4)
)

--Year 05/06
insert into #temp_et
select
CAST(LEFT(pv.pg_expendyrid,2) AS int)[Year],
eg.pg_ethnicgroupname[Ethinicity],
sum([pvstart]) [Starts],

(case when sum(pvstart) = 0 THEN 0 Else convert(decimal(6,3),(sum(pvach)*1.00)/(sum(pvstart)*1.00)*100)end)[Success],
(case when sum(pvstart) = 0 THEN 0 Else convert(decimal(6,3),(sum(pvcomp)*1.00)/(sum(pvstart)*1.00)*100)end)[Retention],
(case when sum(pvstart) = 0 THEN 0 Else convert(decimal(6,3),(sum(pvach)*1.00)/(sum(pvcomp)*1.00)*100)end)[Achievement]
--into temp_et
from [FECAS].Proachieve.dbo.pv_midpoint pv
left join [FECAS].Proachieve.dbo.GN_AggCourseStructure gn on pv.pg_aggcourseid = gn.pg_aggcourseid
left join [FECAS].Proachieve.dbo.PG_ethnicGroup eg on pv.pg_ethnicgroupid = eg.pg_ethnicgroupid

where pv_midpointid = @mpid
and pg_expendyrid = '05/06'

and pv.pg_aggcourseid LIKE 'E2%'

group by
eg.pg_ethnicgroupname,
pv.pg_expendyrid
order by
eg.pg_ethnicgroupname

View 14 Replies


ADVERTISEMENT

Showing Records Where Count(*) Is Zero (in A Stored Proc)

Jul 20, 2005

This seems so easy....change the join to show all records, but thezero records still do not showI want to join 2 tables....basically Customers and Orders....get thetotal number of orders for each Customer within a date range...but Ican't seem to show records where the total for a particular Customeris zero (which is very important info)There must be an easy way???thanks,Paul

View 2 Replies View Related

2 Records Not Showing In Report But They Can Be Retrieved From DB Using Same SQL Statement

Jan 21, 2008

Hi,

I have a report with 5 filters which can be applied to it. The records are grouped by the Rotation programme there are on, with a subtotal for each unique programme name.

The report seems to work fine, but upon closer inspection - we noticed that 2 of the records are not being displayed. As a result, the total count is out by 2.

We tracked down the missing records so I ran the SQL query with a Where clause, and it was able to find the two records.

What could possibly cause this behaviour? Please see included SQL statement :





Code Block

SELECT Posts.PostNumber,COUNT(Posts.PostNumber) AS RPCount, Incumbents.Name AS IncumbentName, Grades.GradeTitle, Specialties.SpecialtyTitle,
Hospitals.Name AS Hospital, Genders.Gender, [Incumbent History].YearGraduated, COUNT([University Origins].Origin) AS OriginCount,
Incumbents.Nationality AS NationalityID, Countries.[Country Name] AS Nationality, [Rotation Programmes].[Programme Name],
Posts.[Post Approved for Training], [University Origins].Origin, Posts.OldPostNumber, [Rotation Programmes].[Programme ID]
FROM Posts INNER JOIN
Incumbents ON Posts.PostNumber = Incumbents.PostNumber INNER JOIN
[Incumbent History] ON Incumbents.[Incumbent ID] = [Incumbent History].IncumbentID INNER JOIN
Grades ON Incumbents.[Official Grade] = Grades.GradeID INNER JOIN
Specialties ON Posts.Specialty = Specialties.SpecialtyID INNER JOIN
Hospitals ON Posts.HospitalID = Hospitals.[Hospital ID] INNER JOIN
Genders ON Incumbents.GenderID = Genders.GenderID INNER JOIN
Countries ON Incumbents.[Country Of Birth] = Countries.[Country ID] INNER JOIN
[Rotation Programmes] ON Posts.[Rotation Programme] = [Rotation Programmes].[Programme ID] INNER JOIN
[University Origins] ON [University Origins].[Uni Origin ID] = Incumbents.[University Origin]

GROUP BY [Rotation Programmes].[Programme Name], Posts.PostNumber, Incumbents.Name, Grades.GradeTitle, Hospitals.Name, Genders.Gender,
[Incumbent History].YearGraduated, [University Origins].Origin, Incumbents.Nationality, Countries.[Country Name], [University Origins].Origin,
Posts.[Post Approved for Training], Posts.OldPostNumber, Specialties.SpecialtyTitle, [Rotation Programmes].[Programme ID]

View 12 Replies View Related

Table Diff Utility - Showing Only Difference Of Records

Dec 10, 2007

Hi Madhu,


my table does not have primary key so i created a seperate index on each of the table.

I used the recommended tablediff utility and it works successfully. But its only show the difference of records in each table and does not copy rows from source to destination and destination to source table. I was expecting database1.dbo.table1 contains same records as in database1.dbo.table2.


C:Program FilesMicrosoft SQL Server90COM>tablediff /sourceserver kashif-pcs
qlexpress /sourcedatabase AB /sourcetable table1 /destinationserver kashif-pcsq
lexpress /destinationdatabase CD /destinationtable table2
Microsoft (R) SQL Server Replication Diff Tool
Copyright (C) 1988-2005 Microsoft Corporation. All rights reserved.

User-specified agent parameter values:
/sourceserver kashif-pcsqlexpress
/sourcedatabase AB
/sourcetable table1
/destinationserver kashif-pcsqlexpress
/destinationdatabase CD
/destinationtable table2

Table [AB].[dbo].[table1] on kashif-pcsqlexpress and Table [CD].[dbo].[table2]
on kashif-pcsqlexpress have 5 differences.
Err Sno
Src. Only 101
Src. Only 102
Dest. Only 103
Dest. Only 104
Dest. Only 105
The requested operation took 0.466767 seconds.



Can you write a short script for my problem, just like comparison of database1.dbo.table1 compares in database2.dbo.table2 and which ever records not present it should copy those and vice-versa.

It means Database1.dbo.table1 contains 5 records
Database2.dbo.table2 contains 5 records




Regards
Kashif Chotu

View 3 Replies View Related

SQL 2012 :: Query To Make Single Records From Multiple Records Based On Different Fields Of Different Records?

Mar 20, 2014

writing the query for the following, I need to collapse the continuity. If the termdate for an ID is one day less than the effdate of the next id (for the same ID) i need to collapse the records. See below example .....how should i write the query which will give me the desired output. i.e., get min(effdate) and max(termdate) if termdate is one day less than the effdate of next record.

ID effdate termdate
556868 1999-01-01 1999-06-30
556868 1999-07-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-01-31
556872 2004-02-01 2004-02-29

output should be ......

ID effdate termdate
556868 1999-01-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-02-29

View 0 Replies View Related

Query Showing Tablesize In MB

Jul 5, 2004

Hello all,

Is there an SQL query that can be run against a database that displays both the number of rows and the physical size of the tables in that database?

I'm basically after the information displayed in Taskpad view >> Table Info, but in an easy to manipulate and publish format.

Thanks for your time.

View 5 Replies View Related

Data Not Showing In MS Query But It Is In The Sql Server Db ...

Sep 28, 2007

Hello all,



I have a simple query "Select distinct batch_id from batch WHERE batch_id = 123 or batch= 345



I run this query in MS query on the proper db and it gives me nothing.

I run the same query in the sql server console and the data is there.



As mentioned I am on the proper db since it works fine for some of my batch_id's for the 2 most recent one !!!??? They are in the db but I cant select them ....


Any idia ?

View 4 Replies View Related

Creating A Query Showing File Not Existing

Jan 16, 2008

This is a SQL question while using Microsoft SMS.

I am trying to write a SQL query looking for a specific file in a specific directory. If the File does not exist, then I want it to display.

here is the Code that I have for it that shows that the file exists... how do I make it show that the file doesn't exist?... what am I doing wrong?

Thanks for all your help in advance!

**********************************

SELECT TOP 100 PERCENT SYS.Netbios_Name0, SYS.User_Name0, SF.FileName, SF.FileVersion, SF.FileSize, SF.FileModifiedDate, SF.FilePath,
SYS.Operating_System_Name_and0
FROM dbo.v_GS_SoftwareFile SF INNER JOIN
dbo.v_R_System SYS ON SYS.ResourceID = SF.ResourceID
WHERE (SF.FileName = 'UdaterUI.exe')
AND (SF.FilePath = 'C:Program FilesMcAfeeCommon Framework')
OR
(SF.FileName = 'UdaterUI.exe')
AND (SF.FilePath = 'c:Program FilesNetwork AssociatesCommon Framework')
ORDER BY SF.FileVersion, SYS.Netbios_Name0

View 1 Replies View Related

Select Query - Showing Columns Data Row Wise

Dec 28, 2011

I have get 3 columns in a select query. how can show these 3 columns in row wise.

View 2 Replies View Related

SQL Server 2012 :: Query Execution Not Showing Up In Profiler Trace

Aug 22, 2014

Set up a trace with the events RPC:Completed, SQL:BatchCompleted, SQL:BatchStarting, and SQL:StmtCompleted.

When I issue the statement: SELECT * FROM XyzView there is nothing captured in Profiler. If I script out the view and then execute the select statement that defines the view, it does show up in Profiler.

I've tried adding a lot of the other events, i.e. SP:StmtCompleted and the various other StmtStarting events and the trace still does not capture anything.

Am I capturing the wrong events or is this known behavior? My goal is to see what the overhead is for using a view versus persisting the results of the view as a table and referencing that instead. The view in question is against static data, joins 9 tables, and is referenced a lot.

I can use the stats generated when I execute the select that defines the view but I still find this to be curious behavior so I assume I'm doing something wrong.

View 9 Replies View Related

Need Efficient Query To Partition Records By Type And Pull Top N Records From DB

Jan 18, 2008

I have a query similar to the following. The intent of this query is to retrieve the top 6 records meeting the specified criteria (LOGTYPENAME = 'Process Status Start' OR LOGTYPENAME = 'Process Status End' ) based on most recent dates. Please keep in mind that I expect to return up to 6 records for each unique LogProcessName. This could be thousands of different LogProcessNames with up to 6 records for each.

1) The table I am executing against currently is very large in size and thus takes a long time to execute against. It would seem there must be a more efficient query to get the results I am looking for?
2) CTE doesn't work on SQL 2000. I need a query that does.
3) I cannot modify the database itself in the process.


;WITH cte AS (
SELECT [LogProcessName], [LogBody], [LogDate], [LogGUID], row_number()
OVER(PARTITION BY [LogProcessName]
ORDER BY [LogDate] DESC)
AS RN
FROM [LOGTABLE]
WHERE [LogTypeGUID] IN (
SELECT LogTypeGUID
FROM LOGTYPE
WHERE LogTypeName = 'Process Status Start'
OR LogTypeName = 'Process Status End' ) )
SELECT *
FROM cte
WHERE RN = 1 OR RN = 2 OR RN = 3 OR RN = 4 OR RN = 5 OR RN = 6
ORDER BY [LogProcessName] DESC, [LogDate] DESC

Does anybody else have any idea that would yield the results that I am looking for and take into account items 1-3 above?

Thanks in advance.

View 4 Replies View Related

SQL Server 2008 :: Balance Sheet Query Showing Wrong Amounts On VAT Accounts Only

May 21, 2015

I have one query which is pulling Balance sheet amounts from SAP Business One database. The query is giving the correct figures for the rest of the accounts except for the VAT Input refundable account 123600 and VAT Output Payable account 221400. The query sums up totals at Title account level(FatherNum) and the above accounts are the title accounts:

SELECT CAST(T0.TransId AS Varchar(30)) AS TransId, CASE WHEN t3.FatherNum IN ('100000', '350000') THEN '-3 OK' ELSE CAST(T0.TransType AS Varchar(30))
END AS TransType, CAST(T0.BaseRef AS VarChar(30)) AS BaseRef, T0.RefDate,T0.Number as Docnum, DATEPART(Month, T0.RefDate) AS JrnMonth, T0.FinncPriod, T1.Account, T1.Debit,
T1.Credit, T1.Debit - T1.Credit AS JrnAmt, ISNULL(T1.SYSCred, 0) AS SysCred, ISNULL(T1.SYSDeb, 0) AS SysDeb, T1.ShortName, T1.Ref1, T1.Ref2,

[code]....

View 8 Replies View Related

SQL SERVER ACCESS DENIED!! BUT Everything Works On MSDE And Works SHOWING RECORDS ON SQL SERVER!! PLEASE HELP

Jul 26, 2004

I've got a popular problem so i get a message that server acces denied! ..

But that what is different in my error.... When i use same setting same database and connection string (on MSDE server) there is no problem...

On SQL server i have got windwos authentication but i added all accounts as ASPNET and SA.... and when i try to connect by

RETTO - name of my server

server=RETTO;uid=sa;pwd=password;database=db1;
or by
Integrated Security=SSPIserver=RETTO;uid=RETTOASPNET;database=db1;

I CAN BROWSE RECORDS THERE ARE NO PROBLEMS WITH CONNECTION!!! but when i try to update or iinsert or delete something in database there becomame this error that access denied or server does not exist!!!


PLEASE HELP I'm FIGHTING WITH THAT FOR OVER 5 DAYS!!!

I MADE FOR MY ACCOUNTS (SA, ASPNET) ALL THINGS ALLOWED AS EXECUTING stored procedures.. OR ACCESING datatables with insert delete and update query WHERE IS THE PROBLEM!!!??

View 3 Replies View Related

How To Make The SSMSE To Return Whole Records Without Any Close Query Form And Re-create Query Form Operation?

Dec 25, 2007

Hi,
I got a problem.
I installed Microsoft SQL Server Management Studio Express 2005 version.
And I created a Compact database.
I created an connection in SSMSE to connect the database and opened a query form.
then, i run the following sql:

Select * from Table1

It returned 3 records to me.
After that, I used program to insert record into this table.
Then i ran this sql again, it still show me 3 records.
I closed the query form, and re-created a new query form, then run the sql, it returned 4 records to me.

Why? It's very strange and difficult to operate, right?
Is there anyone know how to make the SSMSE to return whole records without any close query form and re-create query form operation?

Thanks a lot!

And Merry X'max!!!

View 4 Replies View Related

Comparing 2 Records SQL Query

May 9, 2008

Hey Guys, I have a contacts table that contains          ID, First Name, Last Name, and Phone Number, Date Entered, Changed. Every time, the data is modified and saved, it will insert a new record in the table. So, Ill create a new record for a contact named Ryan, and then come back a day later and update the last name and phone number. So theSQL table would look like...1   Ryan   Scott  818-550-0000  05/08/2008   Null2   Ryan   Peters  000-000-0000  05/09/2008   Null How do I write a  sql query that will run an update after the insert of the second record to fill in the Changed field with the data that changed?So I want to have record 2, end up looking like this... 2   Ryan   Peters  000-000-0000  05/09/2008   LastName,PhoneNumberAny ideas? 

View 8 Replies View Related

Duplicate Records Query

Jul 9, 2001

Can anyone help me to write a query to show customers who have duplicate accounts with Email address, first name, and last name. this is the table structure is Customer table

customerid(PK)
accountno
fname
lname


Records will be

like this

customerid accountno fname lastname
1 2 lori taylor
2 2 lori taylor
3 1 randy dave


Email

emailid (PK)
customerid
emailaddress

View 2 Replies View Related

Query To See Only Duplicate Records

Dec 16, 1999

How can I made a query to show only my duplicate records ?
For some reason that i do not know, i have duplicate entries in my clustered index 21 duplicate records in a table how can i query to know those 21 duplicate records ?

Thanks

View 2 Replies View Related

Count Records In A Top 10 Query

Dec 5, 2005

Hi

Im trying to make a top 10 list of col1 and and at the 11:th place it should show a number of record that dosent make it to the top 10 list...

i have this so far, and it dosent give me anything...

col1 is varchar 254

SELECT COL1, COUNT(*) AS number
FROM MYTABLE
WHERE (NOT EXISTS
(SELECT TOP 10 COL1
FROM MYTABLE))
GROUP BY COL1
ORDER BY COUNT(*) DESC)

ex of output

place1 100
place2 50
place3 25
...
place11 500

a query that only gives me the place11 number is enough

thx in advance //Mr

View 1 Replies View Related

Query To Eliminate The Records

Apr 7, 2008

Hai

I have written one select statement and it returns the following records.

SELECT a.Name, b.address FROM tbl1 a INNER JOIN tbl2 b ON a.id=b.id

Name address
AAA XYZ
BBB
CCC
DDD

My requirement is to display only if address fields contain values.
For Eg. I want to display AAA XYZ record only. How can I write a query.

Help me.

Kamal..

View 3 Replies View Related

Eliminating Records In A Query

Sep 29, 2014

Need to eliminate certain records from my query. The below is a simple query to illustrate my problem

My Query

Select RequestNo,Event_type from Event_log where Event_type in (10,20)

Data
RequestNo Event_type
123456 10
123457 10
123457 20
123458 10
123459 10
123459 20

This above query returns all requests that meets atleast one criteria. How do i edit my query such that i get requests that meet both criteria and the result set looks like below

Data

RequestNo Event_type
123457 10
123457 20
123459 10
123459 20

View 2 Replies View Related

Query Quantity Of Records

Nov 20, 2014

I need to query SQL Server Express 2012 records to find 6 serial numbers that are all assigned to one common unique number. Normally in this use case, 12 serial numbers are assigned to one common unique number, so I'm trying to find the odd entry.

View 2 Replies View Related

Insert Records Using Sub-query

Apr 1, 2015

Create a new table named frequent travelers (FreqTrav). It will only store passengers who have taken more than 2 trips with the company. It will record the passenger name, passenger number, address, phone number, total trips and total fare paid. Show your CREATE TABLE query and INSERT query. Please insert the records using subquery (i.e. insert from a SELECT query).

CREATE TABLE FreqTrav (
PASSENGERNUM INT(20)
CHECK (PASSENGERNUM IN

[code]...

but It's not working for me since I tried inserting a passengernum who did't travel more than two times and it was inserted.Is there any way I can answer without using check constraint.

View 3 Replies View Related

Sql Query For Displaying Records

Aug 9, 2007

Hi,

I would like to know how would i display following data.

exa:- (Note:- I wrote '---' so to display properly in to the forum

Table1
ComputerName--IpAddress
ABC1-----------10.1.2.3
ABC1-----------10.1.2.4
ABC1-----------10.1.2.5
ABC2-----------10.1.2.6
ABC2-----------10.1.2.7
ABC3-----------10.1.2.8
ABC3-----------10.1.2.9
ABC4-----------10.1.2.10

Table2

ComputerName--NetCard
ABC1-----------<card1>
ABC1-----------<card2>
ABC2-----------<card3>
ABC2-----------<card4>
ABC3-----------<card5>
ABC3-----------<card6>

Table3
ComputerName--Model
ABC1-----------DEll
ABC2-----------DEll
ABC3-----------DEll

Now i want output should be displayed like this

ComputerName--IpAddress--NetCard Model
ABC1-----------10.1.2.3---<card1>---DEll
----------------10.1.2.4---<card2>
----------------10.1.2.5

ABC2-----------10.1.2.6---<card3>---DEll
----------------10.1.2.7---<card4>

ABC3-----------10.1.2.8---<card5>---DEll
----------------10.1.2.9---<card6>

ABC4-----------10.1.2.10

Black filled should not displayed anything

Is it possible


--------------------
Thanks and regards
Abhishek Joshi
India- Bangalore

View 4 Replies View Related

How To Query For Records That Have Not Been Replicated

Jul 23, 2005

Hi,I am using Merge Replication for synchronizing a bunch of laptopsrunning MSDE with a central SQL Server 2000 production server.This database is used by an application that needs to know whichrecords have not yet been replicated, at any givem time.Here's a simple scenario:User A in laptop X starts his copy of the application. He syncs hisMSDE database through the application, to match the current centralservers' data. He then proceeds to add new records through theapplication and, after he is done, he synchronizes his database withthe central server, through the application.At any given time, the user might kill the application. He might addsome records today, a few more tomorrow or in a week and should be ableto change and delete records that have not yet been merged into theproduction server.The problem is that SQL Server does not have an easy way to tell whichrecords in the subscription tables have been inserted but not yetreplicated. I have been using the following query:SELECT rowguidFROM [MyTable]INNER JOIN (SELECT rowguid AS rep_idFROM msmerge_contentsWHERE generation = joinchangegen AND generation = (SELECT MAX(generation)FROM msmerge_genhistory )) dtableON rowguid_rep = dtable.rep_idThis query works for most cases but fails to identify the first recordcreated immediatly after a synchronization event.What I would like to know is if there is a correct way of identifyingrecords which are "not-yet-replicated" on a given table that is part ofa merge replication process like the one described above.Thanks in advance.

View 1 Replies View Related

How To Get Last Records In Grouped Query.

Jan 23, 2007

Hi,I want to create query where I could group records by quarters, and getthe last record in each group.e.gCreate Table MyTable(Value [float],date[datetime])Insert into MyTable (value, [date]) values (100, '1-1-2000')Insert into MyTable (value, [date]) values (110, '1-2-2000')Insert into MyTable (value, [date]) values (120, '1-3-2000')Insert into MyTable (value, [date]) values (130, '1-4-2000')Insert into MyTable (value, [date]) values (140, '1-5-2000')Insert into MyTable (value, [date]) values (150, '1-6-2000')Insert into MyTable (value, [date]) values (160, '1-7-2000')Now I would like to get this data grouped by quarter, and get the lastvalue from each quarter. So here I would like to get result like this(120, q1 -2000)(150, q2 -2000)(160, q3 -2000)I know how to create aggregate functions but I have problem with gettingthat last record from each group.*** Sent via Developersdex http://www.developersdex.com ***

View 2 Replies View Related

SQL Query - Fetching Records

Oct 1, 2006

Have a table with following structure

ID DeviceName Status
1 Sony Good
2 Toshiba OK
3 Sony Bad
4 Tata OK

I need to return the following records

ID DeviceName Status
2 Toshiba OK
3 Sony Bad
4 Tata OK

If there are more than one record for the Device, then record with the latest ID should be returned.
If there is only one record for the Device, then that record should be returned.

Can this be achieved through a single query.
Any help is appreciated.

Thanks,
Loonysan

View 1 Replies View Related

Help With Query To Reduce Records

Dec 13, 2007

I want to write a quick one time query to create a new table based off an existing table. The idea is to make the new table more efficient by reducing the amount of records...see example below


id1 id2 country
1 2 US
3 4 AU
5 6 US
7 8 US
9 10 PE
11 12 PE
13 14 US
15 16 US
17 18 US
19 20 US
21 22 US


id1 id2 country
1 2 US
3 4 AU
5 8 US
9 12 PE
13 22 US

View 10 Replies View Related

SQL Search :: Query To Sum Records?

May 4, 2015

having some issues trying to create a query in excel 2013. I can get the data I want from sql, but I get individual transactions and I want to sum them by plu number. here is my query, I tried using group by but every time I add the field, I get an error that some other field is invalid because it's not contained in an aggregate or group by clause. btw, I didn't name these fields.

SELECT RPT_ITM_D.F254 as [Date], RPT_ITM_D.F01 As [PLU], RPT_ITM_D.F64 As [Qty Sold], RPT_ITM_D.F65 As [SOLD], OBJ_TAB.F17 As [RCode], OBJ_TAB.F29 As [Description], PRICE_TAB.F30 As [EL Price], PRICE_TAB.F31 As [Qty]
FROM STORESQL.dbo.OBJ_TAB OBJ_TAB, STORESQL.dbo.PRICE_TAB PRICE_TAB, STORESQL.dbo.RPT_ITM_D RPT_ITM_D
WHERE OBJ_TAB.F01 = RPT_ITM_D.F01 AND OBJ_TAB.F01 = PRICE_TAB.F01 AND PRICE_TAB.F01 = RPT_ITM_D.F01 AND ((RPT_ITM_D.F254>=? And RPT_ITM_D.F254<=? )AND (OBJ_TAB.F17=25))

View 8 Replies View Related

Returning ALL Records In A Query

Aug 18, 2006

I'm building a db to collect equip fault data in SQL 2005 and need to modify my query to be able to select/display "ALL" records. I'm currently using a sp to assign a shift to each record and then have a query to select all records by shift. I'd like to add an option to the query to be able to select ALL records, regardless of shift. I've included the sp & query I am currently using. Any help would be appreciated.

Thanks

ALTER PROCEDURE [dbo].[p_dtu_Store_Line_Fault_Data]
-- Add the parameters for the stored procedure here
@AssetID int,
@Timestamp datetime,
@FaultCode int,
@State int
AS
BEGIN
SET NOCOUNT ON;
IF @State = 3
BEGIN
INSERT LineFaultData (FaultCode, AssetID, StartTime, Duration, Shift)
VALUES (@FaultCode, @AssetID, @Timestamp, 0,
CASE WHEN DATEPART(hh,@Timestamp) BETWEEN 7 AND 14 THEN 'DAYS'
WHEN DATEPART(hh,@Timestamp) BETWEEN 15 AND 22 THEN 'AFTERNOONS'
ELSE 'NIGHTS'
END)
END

IF @State <> 3
BEGIN
DECLARE @Count int
SET @Count = (SELECT Count(*) FROM LineFaultData WHERE AssetID = @AssetID AND Duration = 0)
IF @Count <> 0
BEGIN
DECLARE @StartTime datetime
SET @StartTime = (SELECT Top 1 StartTime FROM LineFaultData WHERE AssetID = @AssetID and Duration = 0)
UPDATE LineFaultData
SET Duration = DateDiff(s,@StartTime, @Timestamp)
WHERE AssetID = @AssetID and Duration = 0 and StartTime = @StartTime

END
END

END




SELECT TOP (1000) dbo.LineFaultDescription.Station, dbo.LineFaultData.StartTime, dbo.LineFaultData.Duration, dbo.LineFaultDescription.FaultDescription,
dbo.LineFaultDescription.FaultCategory, dbo.LineFaultData.Shift
FROM dbo.LineFaultDescription INNER JOIN
dbo.LineFaultData ON dbo.LineFaultDescription.FaultCode = dbo.LineFaultData.FaultCode AND
dbo.LineFaultDescription.AssetID = dbo.LineFaultData.AssetID
and (StartTime < '{@End Date}' and StartTime > '{@Start Date}')

WHERE (dbo.LineFaultData.AssetID = {Asset_ID})
AND (dbo.LineFaultData.Shift = '{@Shift}')
ORDER BY dbo.LineFaultData.StartTime DESC

View 4 Replies View Related

Query To Merge Duplicate Records

Jun 6, 2007

Hello,
I have the following Query:
1    declare @StartDate char(8)2    declare @EndDate char(8)3    set @StartDate = '20070601'4    set @EndDate = '20070630'5    SELECT Initials, [Position],  DATEDIFF(mi,[TimeOn],[TimeOff]) AS ProTime6    FROM LogTable WHERE 7    [TimeOn] BETWEEN @StartDate AND @EndDate AND8    [TimeOff] BETWEEN @StartDate AND @EndDate9    ORDER BY [Position],[Initials] ASC
The query returns the following data:
Position                                           Initials ProTime     -------------------------------------------------- -------- ----------- ACAD                                               JJ       127         ACAD                                               JJ       62          ACAD                                               KK       230         ACAD                                               KK       83          ACAD                                               KK       127         ACAD                                               TD       122         ACAD                                               TJ       127        
  
What I'm having trouble with is the fact that I need to return a results that has the totals for each set of initials for each position.  For Example, the final output that I'm looking to get is the following:
Postition                       Initials                 ProTime
ACAD                           JJ                       189ACAD                          KK                       440ACAD                          TD                        122ACAD                          TJ                         127
 Any assistance greatly appreciated.

View 3 Replies View Related

Update Query Not Upadting Records?

Aug 19, 2007

dear experts,
The code written below doesnt report any error and doest serve the objective of updating the record in the database. Can you please suggest what can be the problem?
 Public Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim conLath As SqlConnection        Dim comLath As SqlCommand        Dim upcmd
        conLath = New SqlConnection("Data Source=heybabe1;Initial Catalog=sexsg;User ID=sa;Password=password")        conLath.Open()
        upcmd = "Update Hist set sett_price=@s_p, post_close=@p_s, vol_oq=@v_oq where hist_id=@hid"
        comLath = New SqlCommand(upcmd, conLath)
        comLath.Parameters.Add("@s_p", Data.SqlDbType.Decimal, 8)        comLath.Parameters.Add("@p_s", Data.SqlDbType.Decimal, 8)        comLath.Parameters.Add("@v_oq", Data.SqlDbType.Int, 8)        comLath.Parameters.Add("@hid", Data.SqlDbType.Int, 8)
        comLath.Parameters("@s_p").Value = IIf(sett_price.Text = "", DBNull.Value, sett_price.Text)        comLath.Parameters("@p_s").Value = IIf(post_close.Text = "", DBNull.Value, post_close.Text)        comLath.Parameters("@v_oq").Value = IIf(vol_oq.Text = "", DBNull.Value, vol_oq.Text)        comLath.Parameters("@hid").Value = Request.QueryString("hid")
        Try
            comLath.ExecuteNonQuery()            Response.Redirect("admindata.aspx")
        Catch ex As SqlException            If ex.Number = 2627 Then                Message.InnerHtml = "ERROR: A record already exists with " _                   & "the same primary key"            Else                '     Message.InnerHtml = "ERROR: Could not update record, please ensure the fields are correctly filled out"                Message.InnerHtml = ex.Number                Message.Style("color") = "red"            End If        End Try        comLath.Dispose()        conLath.Close()
    End Sub

View 5 Replies View Related

Update Records Just Selected (in One Query)

Mar 28, 2006

I have a stored procedure that I give some parameters and it joins a couple of tables and returns the results.  I would like to know how to update the records in one of the original tables before returning results.
CREATE Procedure dbo.DS_GetSomething(@someValue char(5)AS
Select table1.* ,table2.* FROM table1 left inner join table1.itemid on table2.itemid where table2.someValue = @someValue
The table has a field of IMPRESSIONS that I would like to do something like:
;UPDATE table1 set impressions=impressions + 1 where recordid=??
I don't know how to access the recordids I just got from the original select statement.
Thanks for any help
Greg

View 7 Replies View Related

Retrieving The First N Records From A SQL Query In VS 2005

Apr 6, 2006

Hi,
first off, I'm a TOTAL novice at this stuff, I'm just currently blundering my way through a complex site to learn stuff.
I'm trying to call the newest addition to a SQL database into a webpage, in this case, it'll be 'newest user', one result only. I've done several other data retrival sections using a datatable, but the guy who was helping me though it is unavailable at the moment and I get the feeling I've jumped into the deepend slightly.
Could anyone give me an example of how retrieving the First N Records from SQL should look in VS? Does it need to be in a data table or can it go in a label?
Sorry if this is somewhat vague, but as I said, I've really only been using VS for a week!

View 3 Replies View Related







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