Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Lambo
Starting Member
1 Post |
Posted - 2002-08-16 : 12:51:47
|
| Suppose I have the following tables,CREATE TABLE Table1 ( Month TinyInt PRIMARY KEY, AvailableDays TinyInt)CREATE TABLE2 ( User VarChar(10) Month TinyInt UsedDays TinyInt CONSTRAINT Table2ProjectMonthKey PRIMARY KEY (User, Month))And I want to do the following:SELECT T1.Month, SUM(UsedDays) / AvailableDays FROM Table2 T2INNER JOIN Table1 T1 ON T1.Month = T2.MonthGROUP BY T1.MonthSo basically I want to group by Month and then display the month, and the UsedDays across all Users for that month and divide it by the number of AvailableDays. Since month is a primary key, AvailableDays should have 1 to 1 correspondance with month, but I can't execute the query because SQL states AvailableDays is not in an aggregate function or group by clause.How would I accomplish this? I can't group by AvailableDays because the numbers aren't unique, the same number might appear more than once in different months. |
|
|
joldham
Wiseass Yak Posting Master
300 Posts |
Posted - 2002-08-16 : 13:04:38
|
| SELECT T2.Month, Case T1.AvailableDays WHEN 0 then 0 ELSE T2.UsedDays/T1.AvailableDays ENDFROM (SELECT Month, sum(UsedDays) UsedDays FROM Table2 GROUP BY Month) T2 INNER JOIN Table1 T1 ON T1.Month = T2.MonthI hope this is what you wanted.Jeremy |
 |
|
|
r937
Posting Yak Master
112 Posts |
Posted - 2002-08-16 : 18:23:52
|
| actually, you can group by month and availabledaysthe following three queries should all give you the same results -- select month, availabledays from table1 select distinct month, availabledays from table1 select month, availabledays from table1 group by month, availabledaysthe reason these are all the same is the 1=1 relationship of those two columnsso since those are the (only) groups, it wouldn't matter if you inner joined or even cross joined with another table before grouping, because the product rows just "collapse" in the groups -- select table1.month, availabledays from table1 inner join table2 on table1.month = table2.month group by month, availabledaysnow add the aggregate function -- select table1.month, sum(useddays)/availabledays from table1 inner join table2 on table1.month = table2.month group by month, availabledaysshould be good to go (well, except for the divide by zero check -- good call, jeremy)rudyhttp://rudy.ca/rudyhttp://rudy.ca/ |
 |
|
|
|
|
|
|
|