Friday, March 23, 2012
Grouping by $10 Dollar Increments in SQL
dollar increments. I can get it to work by hard coding each group and union
each group, but it is slow. Wondering if anyone knows how to do this with
just one group by
This is what I got so far:
Select Sum(SubTotal), Count(OrderNumber)
From Sales
Group By OrderNumber
Having Sum(SubTotal) <= 10
Union
Select Sum(SubTotal), Count(OrderNumber)
From Sales
Group By OrderNumber
Having 10 < Sum(SubTotal) and Sum(SubTotal) <= 20
Union
Select Sum(SubTotal), Count(OrderNumber)
From Sales
Group By OrderNumber
Having 20 < Sum(SubTotal) and Sum(SubTotal) <= 30
....
Union
Select Sum(SubTotal), Count(OrderNumber)
From Sales
Group By OrderNumber
Having 500 < Sum(SubTotal)
Thanks In Advance,
Tom WingertOn Fri, 9 Sep 2005 13:12:02 -0700, Tom Wingert wrote:
>Been trying to find a way to do group orders by their dollar value in 10
>dollar increments. I can get it to work by hard coding each group and union
>each group, but it is slow. Wondering if anyone knows how to do this with
>just one group by
Hi Tom,
Call me paranoid, but this smells like a homework assignment...
Hint 1: You can use expressions in the GROUP BY clause.
Hint 2: In integer division, the remainder is lost.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||1) Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.
2) Quit thinking like a procedural programmer and think is sets and
tables. Inparticular, auxiliaryt tables like this:
CREATE TABLE ReportRangeAmts
(range_name CHAR(15) NOT NULL,
start_amt DECIMAL (8,2) NOT NULL,
end_amt DECIMAL (8,2) NOT NULL,
CHECK (start_amt < end_amt)),
PRIMARY KEY(start_amt, end_amt)),
INSERT INTO ReportRangeAmts VALUES ('< $10', 0.00, 9.99);
INSERT INTO ReportRangeAmts VALUES ('$10 - $19.99', 10.00, 19.99);
etc.
Since you did not bother to post any DDL to help us, I will make a
guess that you do not have a subtotal column, since that would be
computed, and thus not an attribute of a base table. But you should
have the total amount for each sale.
SELECT R.range_name, SUM(sales_amt), COUNT(order_nbr)
FROM Sales AS S, ReportRangeAmts AS R
WHERE S.sales_amt BETWEEN R.start_amt AND R.end_amt
GROUP BY range_name;|||LOL. Yeah, it's "homework", but I get paid for my homework :).
Not sure what you are trying to get at. Can you give me an example?
Thanks in Advance,
Tom Wingert, Software Engineer
Motorcycle-Superstore.com
"Hugo Kornelis" wrote:
> On Fri, 9 Sep 2005 13:12:02 -0700, Tom Wingert wrote:
>
> Hi Tom,
> Call me paranoid, but this smells like a homework assignment...
> Hint 1: You can use expressions in the GROUP BY clause.
> Hint 2: In integer division, the remainder is lost.
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>|||one more comment:
always use union all unless you really really need union|||one way...
select
convert(int,total)/10 as TenDollarRange,
Count(*) as OrdersInThisRange
from (
select OrderNumber, Sum(SubTotal) as Total
from @.Sales
Group By OrderNumber
) OrderGroup
group by convert(int,total)/10
Tom Wingert wrote:
> Been trying to find a way to do group orders by their dollar value in 10
> dollar increments. I can get it to work by hard coding each group and unio
n
> each group, but it is slow. Wondering if anyone knows how to do this with
> just one group by
> This is what I got so far:
> Select Sum(SubTotal), Count(OrderNumber)
> From Sales
> Group By OrderNumber
> Having Sum(SubTotal) <= 10
> Union
> Select Sum(SubTotal), Count(OrderNumber)
> From Sales
> Group By OrderNumber
> Having 10 < Sum(SubTotal) and Sum(SubTotal) <= 20
> Union
> Select Sum(SubTotal), Count(OrderNumber)
> From Sales
> Group By OrderNumber
> Having 20 < Sum(SubTotal) and Sum(SubTotal) <= 30
> ....
> Union
> Select Sum(SubTotal), Count(OrderNumber)
> From Sales
> Group By OrderNumber
> Having 500 < Sum(SubTotal)
> Thanks In Advance,
> Tom Wingert
>|||OK. My Bad. Newbie mistake. Should have posted the rest of the info.
Thanks for the info,
Tom Wingert
PS:
Like your book. Been helpful plenty of times.
"--CELKO--" wrote:
> 1) Please post DDL, so that people do not have to guess what the keys,
> constraints, Declarative Referential Integrity, data types, etc. in
> your schema are. Sample data is also a good idea, along with clear
> specifications. It is very hard to debug code when you do not let us
> see it.
> 2) Quit thinking like a procedural programmer and think is sets and
> tables. Inparticular, auxiliaryt tables like this:
> CREATE TABLE ReportRangeAmts
> (range_name CHAR(15) NOT NULL,
> start_amt DECIMAL (8,2) NOT NULL,
> end_amt DECIMAL (8,2) NOT NULL,
> CHECK (start_amt < end_amt)),
> PRIMARY KEY(start_amt, end_amt)),
> INSERT INTO ReportRangeAmts VALUES ('< $10', 0.00, 9.99);
> INSERT INTO ReportRangeAmts VALUES ('$10 - $19.99', 10.00, 19.99);
> etc.
> Since you did not bother to post any DDL to help us, I will make a
> guess that you do not have a subtotal column, since that would be
> computed, and thus not an attribute of a base table. But you should
> have the total amount for each sale.
> SELECT R.range_name, SUM(sales_amt), COUNT(order_nbr)
> FROM Sales AS S, ReportRangeAmts AS R
> WHERE S.sales_amt BETWEEN R.start_amt AND R.end_amt
> GROUP BY range_name;
>|||On Fri, 9 Sep 2005 13:40:01 -0700, Tom Wingert wrote:
>LOL. Yeah, it's "homework", but I get paid for my homework :).
Hi Tom,
Oh. Sorry for being paranoid then.
>Not sure what you are trying to get at. Can you give me an example?
I could, but Trey Walpole beat me to it. Check his post in this thread
to see what I had in mind.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Thank you, but which book? I have several and there is now a third
editionof SQL FOR SMARTIES. Oh, my mortgage also says "thank you" ...sql
grouping and summing
date prod class qty
060101 a101 1a 100
060101 a101 1a 100
I would like to have the following:
date prod class qty
060101 a101 1a 200
Any other suggestions would be greatful!!
Thanks in advance
the query to return your desired result would look something like this...
select date, prod, class, sum(qty)
from YourTable
group by date, prod, class
thus what you are saying in this query is aggregate the qty per date, prod, class. So if any of these values are different a new record is created. Thus the same product with two diff. class values would result in two records.
HTH,
Derek
|||Thanks for your help Derek!! I was putting the sum and group opposite of what you said.|||no prob dude, take it easy.Wednesday, March 7, 2012
Group by hour, month etc
Hi All,
I have an orders table which has a filed called OrderTime which is the exact time when the order was received ? I need to write the following queries
1. Get number of orders per year
2. Get number of orders per month (obviously if a month (for example, november) is in a different year, its to be in a different row)
3. Get number of orders per hour
Note: If there are no orders in a year etc, it should return a row with 0.
You need to use the DatePart function in your SQL.|||
1.
select datepart(year, OrderTime), count(*) from table group by datepart(year, OrderTime)
or
select year(OrderTime), count(*) from table group by year(OrderTime)
or
select dateadd(year, datediff(year, 0, OrderTime), 0), count(*) fromtable group by dateadd(month, datediff(month, 0, OrderTime), 0)
2.
select dateadd(month, datediff(month, 0, OrderTime), 0), count(*) from table group by dateadd(month, datediff(month, 0, OrderTime), 0)
3.
select dateadd(hour, datediff(hour, 0, OrderTime), 0), count(*) from table group by dateadd(hour, datediff(hour, 0, OrderTime), 0)
|||
sachinsurana:
Note: If there are no orders in a year etc, it should return a row with 0.
No order for which year ? Year 2008, 2009, 3000 ? You have to define what are the range of year. If you have a calendar table, use it to LEFT JOIN to your table.
then create one on the fly
select [year]
from
(
select 2000 as [year] union all select 2001 as [year] union all select 2002 as [year]
) y
or
make use of this function http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685
Sunday, February 26, 2012
GROUP BY DATEPART issues...
Hi,
I'm trying:
Code Snippet
SELECT SUM(price), DATEPART(month, order_date), DATEPART(year, order_date)
FROM orders
GROUP BY DATEPART(month, order_date), DATEPART(year, order_date)
and, while this executes w/o a problem, I am a bit concerned with my results...
i get a SUM(price) = 2140.21 when running the above SQL for 11/2006
however, when i try:
Code Snippet
SELECT SUM(price)
FROM orders
WHERE order_date BETWEEN '11/01/2006' AND '11/30/2006'
i get a SUM(price) = 1950.45
if i bump the second date up by one day (i.e. '12/01/2006') i get a SUM(price) = 2140.21, the same value as when I used GROUP BY
any help would be greatly appreciated!
Hi,
What is the result of this query
Code Snippet
SELECT SUM(price), month(order_date), year(order_date)
FROM orders
GROUP BY month(order_date), year(order_date)
HAVING month(order_date)=6 AND year(order_date)=2006
If result is 1950.45 then
u try to use like this syntax
else
check your data one by one ..
|||Thank you for the response.
I have tried
Code Snippet
...
HAVING DATEPART(month, order_date) = 11 AND DATEPART(year, order_date) = 2006
and received 2140.21
|||Is the order_date always truncated at midnight? Try replacing "SUM(price)" with "COUNT(*)" with your queries. Do you get the same record counts for November 2006?
Thanks,
Bryan Smith
I'm not sure about order_date being truncated at midnight... order_date is a datetime, so i am assuming that up until 11:59:59.99PM on 11/30, the date parts I am after remain the same.
I ran the COUNT(*) as suggested and get 804 using:
Code Snippet
SELECT COUNT(*)
FROM orders
WHERE order_date BETWEEN '11/01/2006' AND '11/30/2006'
and get 838 when using:
Code Snippet
SELECT COUNT(*), DATEPART(month, order_date), DATEPART(year, order_date)
FROM orders
GROUP BY DATEPART(month, order_date), DATEPART(year, order_date)
the number remains 838 when I add:
Code Snippet
HAVING DATEPART(month, order_date) = 11 AND DATEPART(year, order_date) = 2006and drops to 804 if i add:
Code Snippet
WHERE order_date BETWEEN '11/01/2006' AND '11/30/2006'i am baffled, but then again, i'm no expert
thanks for the assistance!
|||Cool! I think we're on the right track here.
Your original code used "WHERE order_date BETWEEN '11/01/2006' and '11/30/2006'". That means orders created between midnight Nov 1 2006 and midnight at the top of Nov 30 2006. You're dropping orders that occurred from 11/30/2006 12:00:00.001 AM to 11/30/2006 11:59:59.997 PM. That's why the BETWEEN statement gives you 804 records while the DATEPART statement gives you 838 records.
(Please note, SQL Server is only accurate to 3 ms when a datetime data type is used. Times of 11:59:59.998 PM and 11:59:59.999 PM are recorded as 12:00:00.000 AM the next day.)
If you re-write your query to use "WHERE order_date BETWEEN '11/01/2006' AND '11/30/2006 11:59:59.997 PM'" you should get 838 records and your SUM should match the one in the DATEPART query.
Good luck,
Bryan
Ahhh... that makes sense...
would it be correct to assume that the GROUP BY DATEPART... query accurately sums up each months data?
thanks again for your help!
|||It would. It calculates the month of the date without regard for time, so any orders placed at anytime on 11/30/2006 would fall into November.
B.
Friday, February 24, 2012
group by
write a query group by the month part of the date. Is it possible to write
it. if yes how. Any suggestion would be greatly appreciated.
regards
shineSelect col1,col2,col3,MONTH(datecol)
From SomeTable
Group by col1,col2,col3,MONTH(datecol)
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"shine" <shine@.discussions.microsoft.com> schrieb im Newsbeitrag
news:3FA1DE3D-DD75-442B-B969-2367E7406E48@.microsoft.com...
> I've created a table containing columns date, cost, orders etc. I want to
> write a query group by the month part of the date. Is it possible to write
> it. if yes how. Any suggestion would be greatly appreciated.
> regards
> shine|||u can get the month as
select datepart(m,getdate()) This_Month
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"shine" wrote:
> I've created a table containing columns date, cost, orders etc. I want to
> write a query group by the month part of the date. Is it possible to write
> it. if yes how. Any suggestion would be greatly appreciated.
> regards
> shine|||Two problems with the code:
(1) all the months get grouped together, regardless of the year, so the
data is meaningless
(2) You are not allowed to have a function in a GROUP BY in Standard
SQL, so this does not port.
I would use a Calendar table to get a year/month value, do a JOIN and
gorup by that.|||On 19 May 2005 08:44:25 -0700, --CELKO-- wrote:
> Two problems with the code:
> (1) all the months get grouped together, regardless of the year, so the
> data is meaningless
> (2) You are not allowed to have a function in a GROUP BY in Standard
> SQL, so this does not port.
> I would use a Calendar table to get a year/month value, do a JOIN and
> gorup by that.
A Calendar table could be real overkill in this case; it didn't sound as
though there are any data attached to specific dates, like there are in the
traditional holiday calendar table.
To get around both the problems identified above, and to show a possible
meaningful use for the grouping, use this construction:
SELECT col1, col2, col3, theYear, theMonth,
COUNT(*) "OrderCount", SUM(cost) "TotalCost"
FROM (
SELECT col1,col2,col3,YEAR(datecol) "theYear", MONTH(datecol) "theMonth"
FROM SomeTable
)
GROUP BY col1, col2, col3, theYear, theMonth|||Comments inline.
http://www.sqlserver2005.de
--
"--CELKO--" <jcelko212@.earthlink.net> schrieb im Newsbeitrag
news:1116517465.190810.201240@.o13g2000cwo.googlegroups.com...
> Two problems with the code:
> (1) all the months get grouped together, regardless of the year, so the
> data is meaningless
Even this was only a example, to show the teamwork of group functions with
the selection of oher columns. Due to the lack of DDL by the original poster
there was no clue what he wants to do. Sytanx exmaples doesnt alway make
sense since they are only syntax examples (due to the lack of DDL).
> (2) You are not allowed to have a function in a GROUP BY in Standard
> SQL, so this does not port.
Actually you are allowed, unless you mention the function also in your Group
by clause, if you are working on TSQL and you dont wanna port your code,
why should you bother about Standard SQL ?
> I would use a Calendar table to get a year/month value, do a JOIN and
> gorup by that.
group by
write a query group by the month part of the date. Is it possible to write
it. if yes how. Any suggestion would be greatly appreciated.
regards
shineSELECT AVG(cost), DATEPART(mm, datecol)
FROM tbl
GROUP BY DATEPART(mm, datecol)
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"shine" <shine@.discussions.microsoft.com> wrote in message
news:F792B5DB-98C6-48C3-B85C-EE43E2915567@.microsoft.com...
> I've created a table containing columns date, cost, orders etc. I want to
> write a query group by the month part of the date. Is it possible to write
> it. if yes how. Any suggestion would be greatly appreciated.
> regards
> shine|||Example:
use northwind
go
select month(orderdate) as month_number, count(*) as month_cnt
from dbo.orders
group by month(orderdate);
AMB
"shine" wrote:
> I've created a table containing columns date, cost, orders etc. I want to
> write a query group by the month part of the date. Is it possible to write
> it. if yes how. Any suggestion would be greatly appreciated.
> regards
> shine
Sunday, February 19, 2012
Gridview delete behavior change from beta2 in VWD express
Several gridview controls in the project had <Delete> enabled. Just <Delete> mind you. Nothing else for command buttons. They all worked fine with delete queries that use gridview.selectedvalue as the parameter. Every single one stopped working since I've converted from beta 2 to RTM!
Here's what I determined. The delete will only work if the row in the grid is selected first!. Otherwise <selectedvalue> is null when you click on <Delete>.
Is this a bug or what?
I'd be happy to supply more details. I am certain others will report this, but I have yet to find a post here or in any blogs out there that reproduce this problem in the RTM of .NET 2.0
On looking more closely at my earlier implementation of <Delete> I realize that the ParameterSource for the key in the grid is actually set to None in dotnet 2.0 beta 2. And it works fine. It seems to just automatically pick up the grid <datakey> value, even when that is a composite key.
My struggles to make <Delete> work again took me down the road of modifying the parameter values which is how I came to my earlier conclusion. Suffice it to say, that <Delete> in the gridview worked very automatically in beta 2. And now, no matter how much I try, the <Delete> function does not work at all.
I will keep playing with it, to see if there is some workaround other than coding things all over again to do deletes in a much more manual way.
Also, I've definitively reproduced my results by moving a working page back and forth from a .NET 2.0 beta 2 and .NET 2.0 RTM environment. Both in a development machine and W2003 server environments. As soon as I take the working page with <Delete> in the gridview from beta 2 to rtm, the <Delete> feature fails.
Anybody else that has a chance to check this out please let me know if you can reproduce this problem.