Friday, March 30, 2012
Grouping question
SELECT PR_NO,
Total = CASE Items.Use_Item_Calc_Qty
WHEN 0 THEN CONVERT(money, SUM
(items.unit_price * items.qty))
ELSE CONVERT(money, SUM(items.unit_price *
items.qty * ITEM_CALC_QTY))
END
FROM Items
where pr_no = 5816
Group By PR_NO, Use_Item_Calc_Qty
The query is returning two records because a record in
the items table has a value of 0 in Use_item_calc_qty and
another record has a value of one.
What I want to return is only one record showing the
total for the Purchase Request. Can anyone help me with
this. I appreciate it.Vic,
I think this is what you wanted to do (your statement of problem is not
quite clear):
SELECT PR_NO,
Total = CONVERT(money, SUM(items.unit_price *
items.qty * (CASE Items.Use_Item_Calc_Qty when 0 then 1 else
Use_Item_Calc_Qty end)))
FROM Items
where pr_no = 5816
Group By PR_NO, Use_Item_Calc_Qty
hth
Quentin
"Vic" <vduran@.specpro-inc.com> wrote in message
news:000d01c3c0dc$56b27560$a501280a@.phx.gbl...
> I have the following query:
> SELECT PR_NO,
> Total => CASE Items.Use_Item_Calc_Qty
> WHEN 0 THEN CONVERT(money, SUM
> (items.unit_price * items.qty))
> ELSE CONVERT(money, SUM(items.unit_price *
> items.qty * ITEM_CALC_QTY))
> END
> FROM Items
> where pr_no = 5816
> Group By PR_NO, Use_Item_Calc_Qty
> The query is returning two records because a record in
> the items table has a value of 0 in Use_item_calc_qty and
> another record has a value of one.
> What I want to return is only one record showing the
> total for the Purchase Request. Can anyone help me with
> this. I appreciate it.sql
Friday, March 9, 2012
Group by query returning too many rows
Why is this query:
select bp, sum(msg) as 'msg'
from dbo.net_report
where gateway = 'sweden'
and convert(varchar, sqldate, 2) > '02.05.01'
and convert(varchar, sqldate, 2) <= '02.05.31'
group by bp
returning 666 rows, while this query
select bp
from dbo.net_report
where gateway = 'sweden'
and convert(varchar, sqldate, 2) > '02.05.01'
and convert(varchar, sqldate, 2) <= '02.05.31'
group by bp
is only returning 20.
The "correct" result is 20 rows, one for each bp.
The fisrt query returns alot of duplicate bp.
By the way: What is faster: Converting the sqldate field to a varchar and comparing with another varchar, or converting the varchar to a date and then comparing it to the sqldate field ?do you want the SUM of all the msg attributes or the number of msg (messages?) for each bp? try using COUNT(*) in place of the SUM(msg).
In your case you are probably doing table scans due to the convertion of the date attribute to a varchar. SQL Server can efficiently convert and test a (var)char variable to a date attribute + you can take advantage of indexes.|||Sorry, I guess I should have made things clearer.
What I want is the sum of all the numbers stored in the msg column, i.e. the number of msgs for each bp. So the result set should have one row for each bp. This works fine without the sum(msg) part, and the result looks something like this:
HENNES
HENTEXTRA
KANAL5
But when I add the sum(msg) to get the number of messages pr. bp then the result looks like this:
Wow. Something strange just happened. When I ran the query to produce the results I added "order by bp" at the end, and then there was suddenly just one row for each 20 in total. Without it the resultset returns 666 rows.
Is the group by clause dependent upon the order one retrieves the rows ?|||No. The order by is used to sort the result set and does not affect the group by.
I set up a simple test...
Code:
----------------------------
create table #tmp(f1 varchar(10),f2 int)
insert into #tmp values('A',2)
insert into #tmp values('A',4)
insert into #tmp values('C',3)
insert into #tmp values('C',1)
insert into #tmp values('C',1)
insert into #tmp values('B',2)
insert into #tmp values('B',3)
insert into #tmp values('B',4)
select f1,sum(f2) as 'Sum'
from #tmp
group by f1
order by f1
----------------------------
is this anything close to what you are working on?|||That is pretty much what I am working on, except that my view has alot more columns. At the moment I am really only interested in getting one row for each bp, with one sum of messages for each.
My query does produce the desired results, as long as I have the "order by bp" clause at the end.
So my problem is really solved, but I don't really understand why though. If you want to find out why, and need any more information from me just let me know.
The view I am querying is based on two other views, but I can't see that making much of a difference.
This is the result I was looking for, and I get with the order bp:
davinci 1333
E-CLIPS 1864
HENNES 1397
KANAL5 6470
MRJET 6
PASSAGEN 70
SIMONTV 12
SPORTAL 828
STARLIFE 1004
TISCALI 2484
YAHOO 3
...
...
20 rows in total
This is some of what I get without the order bp:
SPORTAL 8
davinci 11
E-CLIPS 11
davinci 1
E-CLIPS 1
davinci 7
E-CLIPS 7
davinci 9
E-CLIPS 9
davinci 2
E-CLIPS 2
davinci 8
...
...
...
666 rows in total
GROUP BY problems...
Code Snippet
SELECT aagfakt.kndnr1,
aagfaktpos.artnr1,
CONVERT (char, aagfaktpos.faktdatum, 104) AS [Datum],
SUM (CASE
WHEN aagfaktpos.storno = 1
THEN aagfaktpos.bestellmenge * -1
ELSE aagfaktpos.bestellmenge
END) AS absatz
FROM aagfaktpos
INNER JOIN aagfakt
ON aagfaktpos.lfdfaktnr = aagfakt.lfdfaktnr
GROUP BY aagfaktpos.artnr1,
kndnr1,
aagfaktpos.faktdatum
ORDER BY kndnr1 ASC;
The data doesn't group, I don't know why... any help would be appreciated!
My suggestion:
Code Snippet
SELECT aagfakt.kndnr1,aagfaktpos.artnr1,
CONVERT (char, aagfaktpos.faktdatum, 104) AS [Datum],
SUM (CASE
WHEN aagfaktpos.storno = 1
THEN aagfaktpos.bestellmenge * -1
ELSE aagfaktpos.bestellmenge
END) AS absatz
FROM aagfaktpos
INNER JOIN aagfakt
ON aagfaktpos.lfdfaktnr = aagfakt.lfdfaktnr
GROUP BY aagfaktpos.artnr1,
aagfakt.kndnr1,
CONVERT (char, aagfaktpos.faktdatum, 104)
ORDER BY aagfakt.kndnr1 ASC;
Wednesday, March 7, 2012
Group by on a concatenate field
Select TOP 100 CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) as CODE, Date_Issued, sum(Amount)
from dbo.Enterprise_Credits_Import_90_days
where CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) <> ' 0' and Service_Prefix like 'F'
Group by ?
How can I group by the field that I selected as CODE?
you have to repeat the expression:
Select TOP 100 CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) as CODE, Date_Issued, sum(Amount)
from dbo.Enterprise_Credits_Import_90_days
where CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) <> ' 0' and Service_Prefix like 'F'
Group by CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code), Date_Issued
select top 100 code, date_issued, sum(amount)
from
(select CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) as CODE, Date_Issued, Amount, Service_Prefix from
dbo.Enterprise_Credits_Import_90_days) c
where code <> '0'
and Service_Prefix like 'F'
group by code, date_issued
But... why do you add an empty string in between? And do you mean LIKE 'F%', rather than LIKE 'F' ?
Don't underestimate the power of table expressions. The optimiser knows what you mean (so there's very little difference to performance), and you can easily make something far more readable that way. You could also have used a CTE, like this:
with c as (select CONVERT(VarChar(10),Service_Prefix)+ '' +
CONVERT(VarChar(10),Service_Code) as CODE, Date_Issued, Amount,
Service_Prefix from
dbo.Enterprise_Credits_Import_90_days)
select top 100 code, date_issued, sum(amount)
from c
where code <> '0'
and Service_Prefix like 'F'
group by code, date_issued
Rob|||
Rob Farley wrote:
Or if you're interested in readability you could make it: select top 100 code, date_issued, sum(amount)
from
(select CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) as CODE, Date_Issued, Amount, Service_Prefix from
dbo.Enterprise_Credits_Import_90_days) c
where code <> '0'
and Service_Prefix like 'F'
group by code, date_issued
SQL Server does not allow grouping by column alias names - does it? Other RDB engines allow this, and even ordinal grouping (group by 1,2, ...) notations but I thought SQL Server required you to repeat the expressions.
|||But this isn't actually grouping by a column alias. It's grouping by a field in a table expression. It would be no different if you created a view which had those fields in it - then you wouldn't see a problem using the view's fields to group by...By wrapping the fields up in a table expression, you can easily circumnavigate the restrictions on SQL Server to repeat those expressions.
Rob|||right - I should have looked more closely at your original query - I didn't see the inline view before...|||:) So has it helped?|||
Im going to test it today. Ill let you know if I get it to work.
Thanks for alll the help !
|||I tried the first statement and was able to make it work. Thanks for the info.
The second query gave me this error
Server: Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'with'.
Also due to the fact that the database has around 6 million records the group by's seem to make the query take a while to run. Is there any way to speed up the query?
Thanks again for your help
|||The second one requires SQL2005 - you'll get an error in SQL2000.Could you get away with grouping by service_prefix and service_code separately, and then only concatenating them in the final select? That way, you could put a useful index on those two fields (plus date_issued, and amount), and it should run much more nicely. A covering index which includes all the fields you're interested in will mean that it doesn't even need to look at the table, because all the info will exist in the index.
Like this:
Select TOP 100 CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) as CODE, Date_Issued, sum(Amount)
from dbo.Enterprise_Credits_Import_90_days
where Service_Code <> ' 0' and Service_Prefix like 'F%'
group by service_code, service_prefix, date_issued
And you have an index on service_code, service_prefix, date_issued, amount
By changing the where clause to filter on the service_code rather than the concatenated field, that will help performance too, because it can then use the index more effectively. If you need to cater for where the 0 can be either in the prefix or in the code, you could always do an extra check... but try to avoid grouping or filtering on calculated fields, which makes it harder for the system to use indexes.
Rob|||
I think I see what you are saying here. The group by on both non concatenated fields should produce the same results as one group by by using the indexes more effectively. Ill try this and let you know. Prob be tommorow. Although in order to do a group by I thought you had to have the the group by fields in the select statement?
Thanks for your help.
|||You don't need to have the group by fields in the select statement, you just can't use fields that aren't either aggregated or one of the grouped fields.But you can certainly select a concatenation of two of the grouped fields - definitely no problem there.
Rob|||
I would be careful about grouping on such a value as this:
Group by CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code), Date_Issued
Instead of doing all of this conversion stuff in the bowels of the query do it either:
1. In the user interface and write the query as:
Select TOP 100 Service_Prefix, Service_Code, Date_Issued, sum(Amount)
from dbo.Enterprise_Credits_Import_90_days
where Service_Code<> '0'
and Service_Prefix = 'F'
Group by Service_Prefix, Service_Code, Date_Issued
2. If you cannot use the UI, then do the conversion in an aggregate. There will be little performance hit because there will only be a single row in every case:
Select TOP 100 Max(CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code)) as CODE,
Date_Issued, sum(Amount)
from dbo.Enterprise_Credits_Import_90_days
where Service_Code<> '0'
and Service_Prefix = 'F'
Group by Service_Prefix, Service_Code, Date_Issued
ANY code appearing in an expression in a where or group by clause (and having, join-on criteria, etc) can cause performance issues that cannot be solved with indexes, like the criteria:
CONVERT(VarChar(10),Service_Prefix)+ '' + CONVERT(VarChar(10),Service_Code) <> ' 0'
Will not perform well because you don't have an index on this expression, and the optimizer would have to figure it out over and over instead of a simple probe into an index.
|||Yes... this is the point I was trying to make.One thing to do it as an intellectual exercise about what you can do with T-SQL, but as soon as you're talking about performance, then you need to consider the fact that you really don't want to use the results of functions for filters/groups/sorts.
Rob|||Not disagreeing with you...Just adding my 2 cents worth to clarify/back you up :)
GROUP BY DateTime
Did a research, seems like the only solution in SQL Server is:
SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
CONVERT(CHAR(8), RecTime , 112);
The RecTime is a DateTime field, and I wish to sort by the Date
Component.
Any simpler solution?<ckkwan@.my-deja.com> wrote in message
news:58c5c9b0-1fd1-43f5-aac3-360c83d7b2a7@.w1g2000prd.googlegroups.com...
> Dear All,
> Did a research, seems like the only solution in SQL Server is:
> SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
> CONVERT(CHAR(8), RecTime , 112);
> The RecTime is a DateTime field, and I wish to sort by the Date
> Component.
> Any simpler solution?
In SQL2000/2005, not really. But really, it's not that complex.
There's variations on this, but they're all about the same idea.
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||ckkwan@.my-deja.com wrote:
> Dear All,
> Did a research, seems like the only solution in SQL Server is:
> SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
> CONVERT(CHAR(8), RecTime , 112);
> The RecTime is a DateTime field, and I wish to sort by the Date
> Component.
> Any simpler solution?
Definitely not the only solution!
Are there any simpler solutions? No. But there is a faster solution.
AFAIK this is the best performing solution:
SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0)
FROM RecTbl
GROUP BY DATEDIFF(day, 0, us_Hitdate)
--
Gert-Jan
SQL Server MVP|||Gert
You meant
GROUP BY DATEADD(day, DATEDIFF(day,0,EstimateDate) ,0)
"Gert-Jan Strik" <sorry@.toomuchspamalready.nl> wrote in message
news:480657AB.F6B90AE9@.toomuchspamalready.nl...
> ckkwan@.my-deja.com wrote:
>> Dear All,
>> Did a research, seems like the only solution in SQL Server is:
>> SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
>> CONVERT(CHAR(8), RecTime , 112);
>> The RecTime is a DateTime field, and I wish to sort by the Date
>> Component.
>> Any simpler solution?
> Definitely not the only solution!
> Are there any simpler solutions? No. But there is a faster solution.
> AFAIK this is the best performing solution:
> SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0)
> FROM RecTbl
> GROUP BY DATEDIFF(day, 0, us_Hitdate)
> --
> Gert-Jan
> SQL Server MVP|||Gert is correct, no need to have the DATEADD in the GROUP BY as it does not
change the grouping. Try this:
SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0), COUNT(*)
FROM (SELECT CURRENT_TIMESTAMP
UNION ALL
SELECT DATEADD(hh, 1, CURRENT_TIMESTAMP)) AS T(us_HitDate)
GROUP BY DATEDIFF(day, 0, us_Hitdate);
Plamen Ratchev
http://www.SQLStudio.com|||Nope :-)
--
Gert-Jan
Uri Dimant wrote:
> Gert
> You meant
> GROUP BY DATEADD(day, DATEDIFF(day,0,EstimateDate) ,0)
> "Gert-Jan Strik" <sorry@.toomuchspamalready.nl> wrote in message
> news:480657AB.F6B90AE9@.toomuchspamalready.nl...
> > ckkwan@.my-deja.com wrote:
> >>
> >> Dear All,
> >>
> >> Did a research, seems like the only solution in SQL Server is:
> >>
> >> SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
> >> CONVERT(CHAR(8), RecTime , 112);
> >>
> >> The RecTime is a DateTime field, and I wish to sort by the Date
> >> Component.
> >>
> >> Any simpler solution?
> >
> > Definitely not the only solution!
> >
> > Are there any simpler solutions? No. But there is a faster solution.
> > AFAIK this is the best performing solution:
> >
> > SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0)
> > FROM RecTbl
> > GROUP BY DATEDIFF(day, 0, us_Hitdate)
> >
> > --
> > Gert-Jan
> > SQL Server MVP|||Plamen
Have you run your script on SS2000?
"Plamen Ratchev" <Plamen@.SQLStudio.com> wrote in message
news:9814BC3D-0B4E-401C-B18D-868581495690@.microsoft.com...
> Gert is correct, no need to have the DATEADD in the GROUP BY as it does
> not change the grouping. Try this:
> SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0), COUNT(*)
> FROM (SELECT CURRENT_TIMESTAMP
> UNION ALL
> SELECT DATEADD(hh, 1, CURRENT_TIMESTAMP)) AS T(us_HitDate)
> GROUP BY DATEDIFF(day, 0, us_Hitdate);
> Plamen Ratchev
> http://www.SQLStudio.com|||Yes, that was a limitation in SQL 2000... But I would assume by today's
standards SQL 2005 is the base to measure. :)
Plamen Ratchev
http://www.SQLStudio.com|||I'd prefer ask people what version they are using. There are still lots of
businesses use SQL Server 2000/
"Plamen Ratchev" <Plamen@.SQLStudio.com> wrote in message
news:6D6390C6-57B3-470F-80FC-8E4DA9F4A3C5@.microsoft.com...
> Yes, that was a limitation in SQL 2000... But I would assume by today's
> standards SQL 2005 is the base to measure. :)
> Plamen Ratchev
> http://www.SQLStudio.com|||Yes, SQL Server 2000 or earlier will not accept the solution I posted.
In that case, it is easier to keep the Selection List items in sync with
the GROUP BY items.
However, if you really wanted to, you could achieve the same thing on
these version by writing:
SELECT DATEADD(day,MAX( DATEDIFF(day,0,my_date_column) ),0)
FROM ...
GROUP BY DATEDIFF(day, 0, my_date_column)
--
Gert-Jan
Uri Dimant wrote:
> I'd prefer ask people what version they are using. There are still lots of
> businesses use SQL Server 2000/
> "Plamen Ratchev" <Plamen@.SQLStudio.com> wrote in message
> news:6D6390C6-57B3-470F-80FC-8E4DA9F4A3C5@.microsoft.com...
> > Yes, that was a limitation in SQL 2000... But I would assume by today's
> > standards SQL 2005 is the base to measure. :)
> >
> > Plamen Ratchev
> > http://www.SQLStudio.com
GROUP BY DateTime
Did a research, seems like the only solution in SQL Server is:
SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
CONVERT(CHAR(8), RecTime , 112);
The RecTime is a DateTime field, and I wish to sort by the Date
Component.
Any simpler solution?
<ckkwan@.my-deja.com> wrote in message
news:58c5c9b0-1fd1-43f5-aac3-360c83d7b2a7@.w1g2000prd.googlegroups.com...
> Dear All,
> Did a research, seems like the only solution in SQL Server is:
> SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
> CONVERT(CHAR(8), RecTime , 112);
> The RecTime is a DateTime field, and I wish to sort by the Date
> Component.
> Any simpler solution?
In SQL2000/2005, not really. But really, it's not that complex.
There's variations on this, but they're all about the same idea.
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html
|||ckkwan@.my-deja.com wrote:
> Dear All,
> Did a research, seems like the only solution in SQL Server is:
> SELECT CONVERT(CHAR(8), RecTime , 112) FROM RecTbl GROUP BY
> CONVERT(CHAR(8), RecTime , 112);
> The RecTime is a DateTime field, and I wish to sort by the Date
> Component.
> Any simpler solution?
Definitely not the only solution!
Are there any simpler solutions? No. But there is a faster solution.
AFAIK this is the best performing solution:
SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0)
FROM RecTbl
GROUP BY DATEDIFF(day, 0, us_Hitdate)
Gert-Jan
SQL Server MVP
|||Gert
You meant
GROUP BY DATEADD(day, DATEDIFF(day,0,EstimateDate) ,0)
"Gert-Jan Strik" <sorry@.toomuchspamalready.nl> wrote in message
news:480657AB.F6B90AE9@.toomuchspamalready.nl...
> ckkwan@.my-deja.com wrote:
> Definitely not the only solution!
> Are there any simpler solutions? No. But there is a faster solution.
> AFAIK this is the best performing solution:
> SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0)
> FROM RecTbl
> GROUP BY DATEDIFF(day, 0, us_Hitdate)
> --
> Gert-Jan
> SQL Server MVP
|||Gert is correct, no need to have the DATEADD in the GROUP BY as it does not
change the grouping. Try this:
SELECT DATEADD(day, DATEDIFF(day,0,us_Hitdate) ,0), COUNT(*)
FROM (SELECT CURRENT_TIMESTAMP
UNION ALL
SELECT DATEADD(hh, 1, CURRENT_TIMESTAMP)) AS T(us_HitDate)
GROUP BY DATEDIFF(day, 0, us_Hitdate);
Plamen Ratchev
http://www.SQLStudio.com
|||Nope :-)
Gert-Jan
Uri Dimant wrote:[vbcol=seagreen]
> Gert
> You meant
> GROUP BY DATEADD(day, DATEDIFF(day,0,EstimateDate) ,0)
> "Gert-Jan Strik" <sorry@.toomuchspamalready.nl> wrote in message
> news:480657AB.F6B90AE9@.toomuchspamalready.nl...