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
--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
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
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]
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
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.
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 ....
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
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.
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?
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,
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!!!??
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?
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?
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
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 ?
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
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.
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.
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.
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 ***
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.
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
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))
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
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.
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
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
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!