I need help using SUM and GROUP BY in SQL Server.
I am generating the query based on 5 tables. I have tried in SQL Server.
Some parts of the query are working, but when I advance the query, I get the wrong results/data.
The problem is that the data is processed twice instead of once on every group by field, e.g. farmer_ID, where the farmer bears or has two or more records.
This happens when i add more tables to the join - on one or two tables, the sum values are okay.
Hence I get farmer_sales = 200 instead of 100.
Kindly let me know how I can get some help
Thanks
David
You can use the outer join (Left or Right) and choose the table that have only one record for each item
Another solution you can use Keyword Distinct before the column name
Nobody here will be able to help without table definitions, the requirements & the query.
With these issues I find it helpful to write the query so you get the proper rows you need. It sounds like you have either dodgy data or incomplete join conditions but it's not possible to tell that without the above. You can debug your data by finding a problem (e.g. farmer_sales) and working through the raw data & query from there. You will have an incomplete PK/FK relationship in your query or a missing constraint allowing bad data. Or you have misunderstood the requirement or the requirement does not makes sense to the data model.
Once you have the query working correctly you can add the aggregations.
One bit of general advice I can give is that adding DISTINCT is almost always the wrong approach.
I am using SQL Server 2008.
I want to select a long list of records and add it to a cursor and iterate through those records to accomplish some task. But I do not know the limitations of this cursor.
Q:
Is there a maximum number of records that the cursor can hold. Or is it unlimited and handled internally using some kind of paging technique to handle the records dynamically.
Code:
DECLARE cursor CURSOR FOR
SELECT C1
FROM T1
This question of mine is not answered for a while now. This is what I have understood. I used cursor to store 12000 records and iterated through it. I worked just fine. So I know for now for less than 12000 records courser works fine.
If you found more on this, please leave a comment of a best answer. I will not hesitate to change that to my correct answer.
I'm doing some updates to an old Classic ASP website. There is a table which contains several columns of text data and a datetime field. I need to get a list of unique years from all of the values in the table. I've tried this:
set objConnection = Server.CreateObject("ADODB.Connection")
objConnection.ConnectionString = "Provider=SQLNCLI10;Server=localhost;Database=mydb;Uid=myuser;Pwd=something;"
objConnection.Open
set objRst = objConnection.execute("SELECT DISTINCT(YEAR(report_date)) AS report_year FROM report;")
if not objRst.eof then
do while not objRst.eof
response.write objRst("report_year")
objRst.movenext
loop
end if
But when I run this script in the page it just does nothing - eventually the script times-out.
Can anyone suggest how to accomplish this? Thanks!
This is going to be an index problem or a locking problem (or both).
First, try to select the data using the NOLOCK hint - this means your select query won't wait for any uncommitted transactions:
set objRst = objConnection.execute("SELECT YEAR(report_date) AS report_year FROM report (NOLOCK) GROUP BY YEAR(report_date)")
do while not objRst.eof
response.write objRst("report_year")
objRst.movenext
loop
If that still hangs it would suggest an index issue, to sort that out you'll need to run the query in SSMS (if you can) and see how long it takes there. If it takes ages in SSMS it would suggest you need to create an index on the report_date column - if it's quick in SSMS then it's something to do with your ASP, i.e. is the connection open? have you tried doing a simple query to make sure that works? i.e.
SELECT TOP 1 YEAR(report_date)
FROM report
EDIT: just noticed your comment regarding the fact that there are only 5 rows in the table - so it's probably not an indexing issue! However the NOLOCK hint and GROUP BY (as opposed to DISTINCT) might help.
Would be interesting to see an execution plan of this too (i.e. make sure there are no triggers slowing things down)
I'm trying to use this query to delete the rows that are already on a linked server's Database:
GO
USE TAMSTest
GO
DELETE from [dbo].[Hour]
WHERE [dbo].[Hour].[InHour] = (SELECT [InHour]
FROM [TDG-MBL-005].[TAMSTEST].[dbo].[Hour])
GO
When there is only 1 row in the linked server's table, SELECT [InHour] FROM [TDG-MBL-005].[TAMSTEST].[dbo].[Hour] returns that single row and the DELETE works as expected. However, with multiple rows in the linked sever's table, it doesn't work since that part of the query returns mutiple rows as its result. How can I work around this?
If there is further information needed please ask, I need to get this done ASAP.
Thanks in advance,
Eton B.
Change your equal sign to an IN statement
DELETE from [dbo].[Hour]
WHERE [dbo].[Hour].[InHour] IN (SELECT [InHour]
FROM [TDG-MBL-005].[TAMSTEST].[dbo].[Hour])
The IN clause allows you to have multiple values in your WHERE clause, and can be used in subqueries as well. Here's more information.
We've got a weird problem with joining tables from SQL Server 2005 and MS Access 2003.
There's a big table on the server and a rather small table locally in Access. The tables are joined via 3 fields, one of them a datetime field (containing a day; idea is to fetch additional data (daily) from the big server table to add data to the local table).
Up until the weekend this ran fine every day. Since yesterday we experienced strange non-time-outs in Access with this query. Non-time-out means that the query runs forever with rather high network transfer, but no timeout occurs. Access doesn't even show the progress bar. Server trace tells us that the same query is exectuted over and over on the SQL server without error but without result either. We've narrowed it down to the problem seemingly being accessing server table with a big table and either JOIN or WHERE containing a date, but we're not really able to narrow it down. We rebuilt indices already and are currently restoring backup data, but maybe someone here has any pointers of things we could try.
Thanks, Mike.
If you join a local table in Access to a linked table in SQL Server, and the query isn't really trivial according to specific limitations of joins to linked data, it's very likely that Access will pull the whole table from SQL Server and perform the join locally against the entire set. It's a known problem.
This doesn't directly address the question you ask, but how far are you from having all the data in one place (SQL Server)? IMHO you can expect the same type of performance problems to haunt you as long as you have some data in each system.
If it were all in SQL Server a pass-through query would optimize and use available indexes, etc.
Thanks for your quick answer!
The actual query is really huge; you won't be happy with it :)
However, we've narrowed it down to a simple:
SELECT * FROM server_table INNER JOIN access_table ON server_table.date = local_table.date;
If the server_table is a big table (hard to say, we've got 1.5 million rows in it; test tables with 10 rows or so have worked) and the local_table is a table with a single cell containing a date. This runs forever. It's not only slow, It just does nothing besides - it seems - causing network traffic and no time out (this is what I find so strange; normally you get a timeout, but this just keeps on running).
We've just found KB article 828169; seems to be our problem, we'll look into that. Thanks for your help!
Use the DATEDIFF function to compare the two dates as follows:
' DATEDIFF returns 0 if dates are identical based on datepart parameter, in this case d
WHERE DATEDIFF(d,Column,OtherColumn) = 0
DATEDIFF is optimized for use with dates. Comparing the result of the CONVERT function on both sides of the equal (=) sign might result in a table scan if either of the dates is NULL.
Hope this helps,
Bill
Try another syntax ? Something like:
SELECT * FROM BigServerTable b WHERE b.DateFld in (SELECT DISTINCT s.DateFld FROM SmallLocalTable s)
The strange thing in your problem description is "Up until the weekend this ran fine every day".
That would mean the problem is really somewhere else.
Did you try creating a new blank Access db and importing everything from the old one ?
Or just refreshing all your links ?
Please post the query that is doing this, just because you have indexes doesn't mean that they will be used. If your WHERE or JOIN clause is not sargable then the index will not be used
take this for example
WHERE CONVERT(varchar(49),Column,113) = CONVERT(varchar(49),OtherColumn,113)
that will not use an index
or this
WHERE YEAR(Column) = 2008
Functions on the left side of the operator (meaning on the column itself) will make the optimizer do an index scan instead of a seek because it doesn't know the outcome of that function
We rebuilt indices already and are currently restoring backup data, but maybe someone here has any pointers of things we could try.
Access can kill many good things....have you looked into blocking at all
run
exec sp_who2
look at the BlkBy column and see who is blocking what
Just an idea, but in SQL Server you can attach your Access database and use the table there. You could then create a view on the server to do the join all in SQL Server. The solution proposed in the Knowledge Base article seems problematic to me, as it's a kludge (if LIKE works, then = ought to, also).
If my suggestion works, I'd say that it's a more robust solution in terms of maintainability.