Current Records Without Subqueries
Apr 23, 2008
I have a table in SQLCE with ProductCode, Age, Rate, Gender, EffectiveDate. I need to get the list of records with the latest effectivedate not later than the current date for the combination of the other fields.
Because it is SQL CE I can't use subqueries.
Thanks.
View 6 Replies
ADVERTISEMENT
Apr 3, 2014
I have a problem with a date in my sql view, I need the records from the 3 last months but without the current month, if I execute my view right now I have the records from January to april but I just need from January to march, I must have always the 3 previous month but I don't know how I can do it
(dbo.frhkrg.fakdat >= DATEADD(MM, - 3, GETDATE()))
View 2 Replies
View Related
May 14, 2007
Hi all
I've been having a really difficult time finding out how to run a query which selects records from an SQL database for the current logged on user. I've tried a whole manner of different approaches but here is where I am at now:
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
ds_meobservingcolleagues.SelectParameters(0).DefaultValue = User.Identity.Name
End If
End Sub
</script>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ds_meobservingcolleagues">
</asp:GridView>
<asp:SqlDataSource ID="ds_meobservingcolleagues" runat="server" ConnectionString="<%$ ConnectionStrings:StPaulsDatabase %>"
SelectCommand="SELECT [observeTeacher], [observeBy], [observeReason] FROM [Observations] WHERE ([observeBy] = @observeBy)">
<SelectParameters>
<asp:Parameter Name="observeBy" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
This is not resulting in any error. But it is not returning the records that it should be either.
Please can anyone help? I'm sure it shouldn't be this difficult to do
View 3 Replies
View Related
Jun 13, 2006
My question is concerned with the three columns below (customerID, RepairDate, CompletedRepair (Yes or No). The column name "CompletedRepair " is blank initially. I need to update the CompletedRepair column with this logic below:
- A customer comes to our store to fix their car, if we fix their problem on the first time and they don’t return later for this same issue, then the
•CompletedRepair column = Y
- If a customer needs to come back to our store to re-fix the same issue within 7 days windows based on the RepairDate on the previous transaction then
•On the last return transaction: CompletedRepair = Y (example: RepairDate =6/12/2006)
•On all previous transactions: CompletedRepair = N (example: RepairDate =6/8/2006, 6/9/2006, 6/10/2006)
- If a customer needs to come back to our store to re-fix the same issue but out of the 7 days windows based on the RepairDate then
•On the last return transaction: CompletedRepair = Y (RepairDate =6/12/2006)
•On the previous transaction: CompletedRepair = Y (RepairDate =6/1/2006)
Every time customer comes to for car repair shop for a new issue or an old issue, we create a new repair transaction in our SQL db. The update on the "CompletedRepair " column will be run every day. Today's records will be run against with last 7 days records (based on Repair Date) to check when customer has been really fixed: the last fix counted Y, the previous fix counted as N but comparison in only 7 days. In other words, a repair today is considered as a completed repair when comparing with last 7 day repairs but it might become not a completed repair if this same customer would come back within next 7 days for the same issue.
The CompletedRepair column is dynamic column and is updated daily by using the logic above.
Below is the expected outcome after we update the Completed Repair column:
CustomerID Repair DateCompleted Repair
ab1 06/12/06 Y
ab1 05/28/06 Y
ab1 05/18/06 Y
ab105/15/06 N
ab1 05/12/06 N
Initially 5/12/06 had Y, when 5/15/06 transaction came, it took the Y and made the 5/12/06 become N. The 5/18/06 transaction did the same to 5/15/06 transaction, made itself Y and converted 5/15/06 into N. The 5/28/06 is Y because comparing with 5/18/06, it is out of 7 days window. The 6/12/2006 is Y because comparing with 5/28/06, it is out of 7 days window.
ab2 06/02/06 Y
ab2 05/28/06 N
ab2 04/19/06 Y
ab2 04/14/06 N
The 4/14/06 transaction initially was Y, it became N when new transaction on 4/19/06 came. Same thing with transactions on 5/28/06 and 6/2/06
ab3 05/11/06 Y
ab3 03/29/06 Y
ab3 03/23/06 N
ab3 03/12/06 Y
The 3/23/06 was Y, when new transaction on 3/29/06 came, it became N and the new transaction is Y. The 5/11/06 is Y because comparing back to 3/29/06, they are out of 7 days window.
ab4 05/11/06 Y
This ab4 customer came to fix her car only one time and don't come back. We supposed the fix was sucessfully and so we mark the CompletedRepair as Y.
I think that I would need to use SQL cursor or case statement for this but I really don't know how to start. Please advice and help me out. Any ideas and suggestion are really appreciated! If you need more information, please let me know!
Thank you!
Tracy
View 4 Replies
View Related
Jun 29, 2015
I am using the following query in a view to retrieve the latest 24 hourly records for a site.This returns 24 hourly records for the last day of measurements at a Site.This works great. However, I now need to retrieve the latest hourly records from the current hour. For example, hours will run from 00:00 to 23:00 and if the query is executed at 15:00, I will return only hourly records for 00:00 to 15:00 etc. I believe I need to filter the result set or modify the query to exclude records greater than the current hour.
View 6 Replies
View Related
Aug 3, 2015
I have some my below requirment to loading some last year and currnet year records for some ID's in my table,
We have to load the ID's that are active at the end of the year for the prior year and ID's that are active as of today for the current year.Here is the scenario when the ID is currently terminated but active at the end of the prior year and the record is not in the table.so, we didn’t load the count for the prior year
Here prior year is 2015-2015 and Current year is 2015-2016
CREATE TABLE remp_year
(ID INT,
STATUS NVARCHAR(100) NULL,
START_DATE DATE NULL,
END_DATE DATE NULL,
date_year nvarchar(10) NULL)INSERT INTO remp_year VALUES (10,'Active','2015-05-26','2015-12-31','2015-2016');
[Code] ...
Here ID 20 and 50 for terminated records is the prior year records so it should count for the last year and those are active in this year those will count for this year.
View 3 Replies
View Related
Jun 16, 2015
I am looking to pull all records for current & previous calendar year in one query. I know how to pull the current calendar year, but how would I pull current & previous?
select id, list_date
from tableA
where list_date > DATEADD(year,-1,GETDATE())
View 5 Replies
View Related
May 27, 2015
My data has 2 fields: Customer Telephone Number, Date of Visit.
Basically I want to add a field ([# of Visits]), which tells me what number of visit the current record is within 6 months.
Customer TN | Date of Visit | # of Visits (Within 6 month - 180 days)
1111 | 01-Jan-2015 | 1
1111 | 06-Jan-2015 | 2
1111 | 30-Jan-2015 | 3
1111 | 05-Apr-2015 | 4
1111 | 07-Jul-2015 | 3
As you can see, the last visit would counts as 3rd because 180 days from 07-Jul-2015 would be Jan-8-2015.
View 3 Replies
View Related
Jun 8, 2008
I've this query
SELECT
t1.ID, t1.Date, t1.Time,
t1.VALUE
FROM RESULT WHERE t1.Date>=CONVERT(VARCHAR(10),DATEADD(d,-7,GETDATE()),101) AND
t1.Date<CONVERT(VARCHAR(10), GETDATE(), 101)
Let's say, current date is 8 AUG 2005 and current time is 2045
So, i will get
ID | Date (this is datetime) | Time (this is integer) | Value
--------------------------------------------------
204 | 8/1/2005| 2359 | 90
205 | 8/1/2005| 2250 | 99
206 | 8/1/2005| 1950 | 88
...
...
207 | 8/7/2005| 1845 | 77
208 | 8/7/2005| 2255 | 77
209 | 8/7/2005| 2140 | 77
Can someone can show me to filter data between
t1.Date>=CONVERT(VARCHAR(10),DATEADD(d,-7,GETDATE()),101) AND TIME>=CurrentTime
t1.Date<CONVERT(VARCHAR(10), GETDATE(), 101) AND TIME<=CurrentTime
If current date is 8 AUG 2005 and current time is 2045, so the result shown as follow
ID | Date (this is datetime) | Time (this is integer) | Value
--------------------------------------------------
204 | 8/1/2005| 2359 | 90
205 | 8/1/2005| 2250 | 99
...
...
207 | 8/7/2005| 1845 | 77
I only have this query,
SELECT
t1.ID, t1.Date, t1.Time,
t1.VALUE
FROM RESULT WHERE t1.Date>=CONVERT(VARCHAR(10),DATEADD(d,-7,GETDATE()),101) AND
t1.Date<CONVERT(VARCHAR(10), GETDATE(), 101)
lack of idea to put the TIME condition.
Plz help me..
View 14 Replies
View Related
Apr 28, 2004
Trying to find which Employees have NOT entered a record (timecard).
Table #1 Employee_Hours
Table #2 Employee (List active)
Table #1
SELECT EID, DATEPART(wk,[Date]) AS Week, MAX([Date]) AS WeekEnding
FROM Employee_Hours
WHERE ([Date] Between '1/1/04' AND '12/31/04')
GROUP BY EID, DATEPART(wk,[Date])
HAVING MAX([Date]) = '1/24/04' --Pay period
Table #2
SELECT EID, DisplayName
FROM Employee
WHERE (Active=1)
I tried subqueries and temp tables but can't get the results I need. The first query will return the employees who entered their time for the given pay period.
Thanks
View 1 Replies
View Related
Jun 15, 2004
Hi,
I have the following sql statement:
INSERT INTO prg_lvl VALUES (
'Data Recovery',
'Data Recovery',
7,
'ENG',
0,
16,
'Menu=w_data_recovery_stk;',
( select max(menu_id) + 1 from prg_lvl ),
'K');
that works for Sybase and I wanna make it works for SQL Server.
The problem is the use ot the subquery (select max(menu_id) + 1 from prg_lvl).
Could I use subqueries in SQL Server in general or is there is any other method to overcome this problem
Thanks,
fady
View 3 Replies
View Related
Oct 14, 2005
Hi,
I would like to know
What is Corelated SubQueries??
Thanks in Advance
View 3 Replies
View Related
Jan 14, 2008
I am very new to SQL Server, working with it in class. I am trying to do procedures involving subqueries using the Northwind database, and am having a rough time.
For instance, I have the following code, which lists all orders for the month of November, 1996:
SELECT Customers.CustomerID, Customers.CompanyName, CAST(Orders.OrderDate AS CHAR (11) )AS OrderDate
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID
AND OrderDate BETWEEN '11/1/1996' AND '11/30/1996' ;
I have been asked to do the same thing, but using a subquery. I came up with the following:
SELECT CustomerID, CompanyName FROM Customers a
WHERE EXISTS (SELECT OrderDate FROM Orders b WHERE a.CustomerID = b.CustomerID
AND OrderDate BETWEEN '11/1/1996' AND '11/30/1996' ) ;
However, it does not list the Order Date, as I want it to, and the information is not correct (it is missing a few orders from November '97 that should show up. Can someone tell me what I am doing incorrectly?
Please note that I do not need anyone to give me the code, but simply give me an idea of what I am doing incorrectly, or let me know how it can be done, so that I may do it. =-)
View 16 Replies
View Related
Apr 12, 2006
Hi all,I've seen mention that you can use nested subqueries down to as manylevels as you like but whenever I run the following:select * from table1where tab1ID in(select tab1ID from table2 where tab2ID in(select tab2ID from Table3 where Tab3ID=N))I get the error "incorrect syntax near the keyword 'where'"Can anyone confirm that sub-subqueries are possible? If so is thesyntax I'm using correct?I'm running SQL 2000 through a Delphi 5 app.RegardsJon
View 2 Replies
View Related
Jul 20, 2005
Guys,Got this query...---------------------------SELECT TOP 5 Tbl_admin_hotels.HotelName,(SELECT COUNT(Tbl_marketing_history.HotelID)FROM Tbl_marketing_historyWHERE Tbl_marketing_history.HotelID = Tbl_admin_hotels.HotelID)AS CountTotal,(SELECT MAX(DateSent)FROM Tbl_marketing_historyWHERE Tbl_marketing_history.HotelID = Tbl_admin_hotels.HotelID)AS LastSentFROM Tbl_admin_hotelsWHERE NOT Tbl_admin_hotels.HotelID = 99ORDER BY CountTotal DESC---------------------------Within the table Tbl_marketing_history there is also a 'Subject' column thatI require, the row to grab this Subject column from should relate to the rowI'm selecting in the SubQuery to grab 'DateSent'.I've tried and tried to grab multiple columns but failed miserably? Cananyone help pleaseeee!Cheers, Ash
View 12 Replies
View Related
Sep 27, 2007
In this stored procedure, I want to grab all the information for Sales Representatives that made less then 6 visits. I have done that in the subquery. But I also want to be able to display their visits by Dates where any number of visits was made. Meaning, i want to be able to show Everyday where a visit was made, but i only want the records that are less then 6 visits. So I want nulls to show up for the dates where no visits were made. So I can track the people that didnt make visits, on days other made visits (which means they should have visits too)
So basically my report looks like this:
09-10-2007 09-11-2007 09-14-2007
Tom Smith 1 3 4
Janice Cooper 3 5 5
Troy Slater 5 4 2
Kelly Short 4 4 4
When i want it to look like this:
09-10-2007 09-11-2007 09-12-2007 09-13-2007 09-14-2007
Tom Smith 1 3 null null 4
Janice Cooper 3 5 null null 5
Troy Slater 5 4 null null 2
Kelly Short 4 4 null null 4
Its an exception report, so i want to show what was not done , on days that are supposed to have things done, i cant show this, if dates are not displayed before there were no visits less then 6. I want to display all relevant dates, where any number of visits was mad. But only show the visits that were less then 6.
Here's my stored procedure that already has the less then 6 visits showing. But doesnt always show the dates. What should i do?
Code Block
SELECT dbo.Qry_Visits.Status,
dbo.Qry_Visits.Customer_code,
Qry_Sales_Group.Name,
dbo.Qry_Sales_Group.SR_Name,
dbo.Qry_Date_Dim.Date_Dimension_Fiscal_Week,
dbo.Qry_Date_Dim.Date_Dimension_Date,
dbo.Qry_Date_Dim.Day_Of_Month,
dbo.Qry_Sales_Group.Region,
dbo.Qry_Visits.period_code,
dbo.Qry_Visits.cycle_day, dbo.Qry_Visits.Visits,
dbo.Qry_Visits.time_log, dbo.Qry_Visits.Mailing_Name,
dbo.Qry_Date_Dim.Date_Dimension_Year,
dbo.Qry_Date_Dim.Date_Dimension_Period,
CONVERT(varchar, dbo.Qry_Visits.time_log, 110) AS Date,
dbo.Qry_Sales_Group.Region_Key, dbo.Qry_Visits.[SR Code],
B.VisitsTotal
FROM dbo.Qry_Visits
INNER JOIN dbo.Qry_Sales_Group
ON dbo.Qry_Visits.[SR Code]
COLLATE SQL_Latin1_General_CP1_CI_AS = dbo.Qry_Sales_Group.SalesPerson_Purchaser_Code
AND dbo.Qry_Visits.[SR Code] = dbo.Qry_Sales_Group.SalesPerson_Purchaser_Code
COLLATE Latin1_General_CI_AS
INNER JOIN dbo.Qry_Date_Dim
ON CONVERT(varchar, dbo.Qry_Date_Dim.Date_Dimension_Date, 110) = CONVERT(varchar, dbo.Qry_Visits.time_log, 110)
INNER JOIN ( Select COUNT(Visits)as VisitsTotal,[Sales Responsible],CONVERT(VARCHAR,(Qry_Visits.time_log),110)TheDate,Qry_Visits.Status
FROM dbo.Qry_Visits
WHERE Qry_Visits.Status=2
GROUP by [Sales Responsible] , CONVERT(VARCHAR,(Qry_Visits.time_log),110),Qry_Visits.Status
HAVING SUM(Visits) < 6)B
ON dbo.Qry_Sales_Group.SR_Name COLLATE Latin1_General_CI_AS = B.[Sales Responsible] COLLATE Latin1_General_CI_AS AND
CONVERT(varchar, dbo.Qry_Date_Dim.Date_Dimension_Date, 110) = B.TheDate
WHERE Qry_Visits.Status=2
ORDER BY dbo.Qry_Sales_Group.SR_Name, CONVERT(varchar, dbo.Qry_Date_Dim.Date_Dimension_Date, 110)
View 5 Replies
View Related
Dec 23, 2007
Hey everyone, I'm running into an issue where I have a select statement that retrieves all employee records from a employee table. In this statement I'm displaying first and last name, titlte and the employees manager id(which is the employees id). What I want is a query that instead of displaying the manager's id, display the manager's name. The query that I'm using below doesn't work. I was hoping that someone could help me out:
SELECT LastName, FirstName, Title, Extension,
(SELECT FirstName, LastName
FROM Employees
WHERE (ReportsTo = EmployeeID)) AS Reports
FROM Employees
Here's the data that I'm using:
LastName, First Name Title Extension Reprots To
Davolio
Nancy
Sales Representative
5467
13
Fuller
Andrew
Vice President, Sales
3457
0
Leverling
Janet
Sales Representative
3355
12
When I run this query I get a error saying "Only one expression can be specified in the select list when the subquery is not introduced with Exists"
Thanks in advance for your help.
View 5 Replies
View Related
Sep 20, 2007
So I already no this can't be done... but I need a suitable alternative (if one exists) so I don't have to competely re-write this already too huge query.
Anyways, in my select I have something like this:
sum( case when code in (1,2,3,4) then 0 else 1 end ) as total
which has now increase from four static values to a more dynamic format, that being a table with 47 values which may shrink or grow over time. Attempting the following fails:
sum( case when code in (select code_id from ExcludedCodes) then 0 else 1 end ) as total
because apparently you can't use selects or aggregates within an aggregate.
So any ideas on how I can get this working... is there no Array or List type variable I could just substitute in? I've already tried using a Table Variable, but that failed as well.
Please keep in mind, this is one line of a very large select containing many other fields and aggregates (on a fair amount of joins) which is used in at least four differerent reporting queries. If there is no quick and easy replacement trick I can do just let me know so I can start re-writing all of them (which is seriously going to make my head hurt).
View 4 Replies
View Related
Dec 23, 2005
Hi, I have searched through this forum and haven't found the answer to a problem I am having so I figured I will post it.
My SQL statement:
Select * FROM tblData WHERE LastName=
(SELECT tblData.LastName FROM tblData GROUP BY tblData.LastName HAVING (Count(tblData.LastName)>1))"
What I am trying to do: I am trying to make an SQL filter that I can apply to my form in order to only show records with duplicate last names. The sub query returns names that are already in the table. I then compare what is found to be duplicate with the original table in order to just show only the duplicate records. Everything works fine as long as there is only one name thats duplicated.
When there are multiple duplicate names then I run into an error.
When the statement is put into a string and executed in VBA I get this error:
"Run-time error '3021': No current record."
When the statement is put into a query and run against the DB I get this error:
"At most one record can be returned by this subquery"
So yeah, any help would be greatly appreciated. Am I going about this all wrong or am I just forgetting something? Thanks for any help.
View 2 Replies
View Related
Jun 15, 2008
Hello,
Lets consider two tables : CUSTOMERS and ORDERS.
I would like to know which of the following query is the fastest:
select * from customers C
where exists (select 0 from ORDERS O
where C.Name like 'A%' and O.Charged = 1)
select * from customers C
where exists (select 0 from ORDERS O
where O.Charged = 1) and C.Name like 'A%'
I don't want to use a JOIN clause. I just want to know if there is a difference of efficiency when the condition on C.Name is inside or outside the sub query.
Thank you in advance for any advices,
regards,
mathmax
View 2 Replies
View Related
Jun 16, 2008
Hello,
I would like to know which of the following query is the fastest:
select * from customers C
where exists (select 0 from ORDERS O
where C.Name like 'A%' and O.Charged = 1 and O.Customers_Id = C.Id)
select * from customers C
where exists (select 0 from ORDERS O
where O.Charged = 1 and O.Customers_Id = C.Id) and C.Name like 'A%'
Because the condition C.Name like 'A%' is inside the sub query, I'm wondering if it will be evaluated for each record of the Orders table. Does anyone know if there is a difference of efficiency when this condition is inside or outside the sub query ?
Thank you in advance for any advices,
regards,
mathmax
View 1 Replies
View Related
Jul 6, 2006
I have tried this insert comand and it errors out telling me that icannot use subqueries this way. INSERT INTO tblPartLocation(PartLocation, Part)VALUES (999,(SELECT PartID FROM tblParts WHEREPartName = 'test'))how would i insert a value from a query?thanks for any help
View 2 Replies
View Related
Apr 20, 2008
I need to build a view that has 4+ columns that are "counts" of relationships with other tables.
for example:
Code Snippet
select Name, Description, (select count(*) from PetOwner PO where PO.OwnerId = O.Id) as PetCount
from O Owner
I need to add a few more counts to this query, but I'm thinking that is a bad idea since the number of joins is going to get out of control if I need more counts.
I've created a view with all the counts and it works fine.
I want to index the view so the counts aren't calculated everytime the query is run, but I can't index if I use a subquery like this.
In the end I want the result set to have these columns.
Code Snippet
Column1, Column2, Count1, Count2, Count3
And I want it to be quick.
What's the best way to do this?
View 1 Replies
View Related
Aug 16, 2007
I have a table with two columns: OID and Cumulative (witch is the same type as OID)
Each OID can have one or more Cumulatives.
Example of data:
OID Cumulative
167 292
167 294
167 296
168 292
169 302
169 304
The cumulation of each OID don't stop at one cumulation, but can be endless (theoretical).
Example: 167->292->590
So the table would have on more row:
OID Cumulative
295 505
I would like to represent this strucuture in a tree view and I'm looking for a query that could give me a table with this structure:
OID Cumul1 Cumul2 Cuml3 Cuml4 .... Cumuln
in the way I can read the row and have as many child nodes as I have values in the columns. The number of columns depends on the row with most cumulations.
How can I do the query?
Is there a better way as my table with n columns?
Thanks for suggestions
View 1 Replies
View Related
Aug 17, 2007
Dear experts,
Recently i got an error msg looks like this: you cannot use subqueries within a sqldatadpter except the subquery is introduced with EXISTS.
Well, actually i was using IN.
I know I can revise my query sting to use INNER JOIN or such stuff just to remove the nested queries. But i'm realllllly curious why it's not allowed??
Really appreciate it if some expert can tell me.
Thanks in advance
View 1 Replies
View Related
Sep 17, 2007
Hi
what i like to do is insert in one table 2 value from 2 different row.
exp:
table1: person
id name
1 bob
2 john
so id like to make an insert that will result in this
table 2: person_knowed
idperson1: 1
idperson2: 2
so the wuery should look something like this:
insert into person_knowed(idperson1, idperson2)(select id from personwhere name = 'bob',select id from personwhere name = 'john'));
anybody have an idea of how to acheive this?
View 1 Replies
View Related
Feb 26, 2008
Hello, How can I do something like:
Insert Into Displayed(snpshot_id, user_id, user_domain, ddisplay, iWidth, iHeight, disp_size, disp_format, watermark, frc_update, creditcost)
Values ((Select snpsht_id from SiteIndex Where user_domain like '%domain'), 1000, (Select domain_id from UserDomains Where user_domain like 'domain'), GetDate(), 480, 360, 2, 1, 1, 0, 3)
Im getting an error:
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Thanks!
View 4 Replies
View Related
May 17, 2000
I wonder if somebody could give me advice on SQL Server7-specific handling of subqueries and backreferences...
What is a) more efficient, and b) faster:
1. IF (DATEDIFF(minute, (
SELECT tLastHitTime
FROM (
SELECT *
FROM tblSession
WHERE tSessionID = 'abcd1234'
) as sess), getDate()) < 30)
SELECT *
FROM sess
or:
2. IF (DATEDIFF(minute, (
SELECT tLastHitTime
FROM tblSession
WHERE tSessionID = 'abcd1234'
) as sess), getDate()) < 30)
SELECT *
FROM tblSession
WHERE tSessionID = 'abcd1234'
In the first example, 2 SELECT statements (line 2 & line 8) refer to derived table by its alias 'sess'. In the 2nd example, both queries are independant, yet identical...
I wonder if SQLServer is "smart" enough to execute identical queries only once, and then reuse the resulset (e.g. derived table), or it requires explicit references (such as alias) in order to do so...
TIA,
Alex
View 2 Replies
View Related
Feb 16, 2007
hi guys,
i have a problem, i have a query which does a search based on a parameter, thing is i want to order them according to how relevant the results are such as 5 for beingan exact match, 0 for being no match. using a series of liek statements.
so that the most relevnat results are displayed at the top.
how do i achieve this - im a bit confused about this.
appreciate any and all help guys
thanks
andy
View 7 Replies
View Related
Jun 15, 2004
hi there,
I have a query that works on sybase and want to make it also works on SQL Server.
The problem is that in this query I 'm using a subquery in an aggregate function.
It seems that SQL Server unlike Sybase doesn't support the use of subquery in aggregate function.
How can I overcome this problem.
Thanks,
Fady
View 3 Replies
View Related
Jun 7, 2006
Hi,
To make a long story short, I'm trying to correlate the most inner query (two levels deep) with the most outer one, and it just doesn't work.
Is it because the correlation must be back-to-back, without any levels that stand before the two?
If you have no idea what I'm talking about, below is the query that does work, but doesn't produce the right results ("QUOTES" gives the same number for all records):
---------------
select printersGlobal.company, (select count(*) from (select subBidding.bid_company from bidding as subBidding where subBidding.bid_company = 'Printing Company 1' group by subBidding.bid_company, subBidding.project) group by subBidding.bid_company) as QUOTES,
count(date_picked) as wins
from printers as printersGlobal
left outer join bidding as biddingGlobal on printersGlobal.company = biddingGlobal.bid_company
group by printersGlobal.company
order by printersGlobal.company asc
----------------------
When I replace 'Printing Company 1' with printersGlobal.company (to correlate and produce dynamic and correct results), I get errors.
I would appreciate if anybody can point me in the right direction.
Thanks.
View 14 Replies
View Related
May 7, 2008
Hopefully someone can suggest a better solution than what I'm currently hobbling along with.
Basically, I've got a table that gets rows inserted (with a timestamp) whenever there is a change to one of the values of a particular "item". So, what I want is to return a dataset of the latest values of each particular item.
I'm guessing that what I'm trying to acheive is doable in some elegant and performant fashion. Something maybe involving a ROLLUP or WITH CUBE or some FANCY item.
But for the time being, I've got a less-elegant query that returns the correct data, just using subqueries.
Here's the T-SQL to run my scenario:
DECLARE @actionHistoryTable TABLE (
itemID int
,actionType int
,actionValue nvarchar(50) NULL
,actionTime datetime )
INSERT @actionHistoryTable VALUES( 1000, 1, 'fork', '1/1/2008')
INSERT @actionHistoryTable VALUES( 1000, 2, '27', '1/2/2008')
INSERT @actionHistoryTable VALUES( 1000, 3, '200', '1/12/2008')
INSERT @actionHistoryTable VALUES( 1000, 2, '1', '1/1/2008')
INSERT @actionHistoryTable VALUES( 1000, 3, '204', '1/1/2008')
INSERT @actionHistoryTable VALUES( 1000, 1, 'ball', '1/3/2008')
INSERT @actionHistoryTable VALUES( 1026, 2, '20', '1/10/2008')
INSERT @actionHistoryTable VALUES( 1026, 2, NULL, '1/5/2008')
INSERT @actionHistoryTable VALUES( 1026, 1, 'hotdog', '1/6/2008')
INSERT @actionHistoryTable VALUES( 1026, 3, '2511', '1/8/2008')
INSERT @actionHistoryTable VALUES( 1026, 3, '375', '1/7/2008')
INSERT @actionHistoryTable VALUES( 1026, 1, 'mustard', '1/5/2008')
INSERT @actionHistoryTable VALUES( 1013, 1, 'rock', '1/2/2008')
INSERT @actionHistoryTable VALUES( 1013, 1, 'paper', '1/21/2008')
INSERT @actionHistoryTable VALUES( 1013, 3, '10', '1/20/2008')
-- JUST DISPLAY THE TABLE FOR EXAMPLE
SELECT * FROM @actionHistoryTable
-- THIS ROLLS-UP THE LATEST VALUE FOR EACH ACTION_TYPE FOR EACH ITEMID
SELECT aht.itemID
,( SELECT TOP 1 aht2.actionValue
FROM @actionHistoryTable aht2
WHERE aht.itemID = aht2.itemID
AND aht2.actionType = '1'
ORDER BY aht2.actionTime DESC ) as 'latest type 1 value'
,( SELECT TOP 1 aht2.actionValue
FROM @actionHistoryTable aht2
WHERE aht.itemID = aht2.itemID
AND aht2.actionType = '2'
ORDER BY aht2.actionTime DESC ) as 'latest type 2 value'
,( SELECT TOP 1 aht2.actionValue
FROM @actionHistoryTable aht2
WHERE aht.itemID = aht2.itemID
AND aht2.actionType = '3'
ORDER BY aht2.actionTime DESC ) as 'latest type 3 value'
FROM @actionHistoryTable aht
GROUP BY aht.itemID
Is there a better way?
-Steve
View 8 Replies
View Related
Apr 7, 2015
I have an existing query, which runs pretty good. However, I need to create a new report, in which I would require to alter the existing query to return two values from each of the subqueries back to the main query.
The following is the current query:
SELECT
tbLogTimeValues.DateTimeStamp as DateTimeStamp
,tbLogTimeValues.FloatVALUE AS Value
FROM
tbLogTimeValues
[Code] ....
Need putting together a query that returns two values from the first sub query (DateTimeStampTemperature and ValueTemperature) and from the second query return (DateTimeStampHumidity and ValueHumidity).
I would simply have to change the Path LIKE '%' + 'Temperature Interval%' within the humidity subquery to read:
Path LIKE '%' + 'Humidity Interval%'
Obviously, I would like to keep the DateTimeStamp comparisons as part of the main query, as the customer has access to this via parameters, and should be the same for both subqueries.
View 3 Replies
View Related