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 |
|
elmojo
Starting Member
1 Post |
Posted - 2010-06-09 : 13:54:14
|
| Example, let's say I have a table with 10 records that look like this:Type Price Quantity ItemT 5.99 15 SocksT 4.49 10 T-ShirtsT 6.99 20 HatsT 15.59 90 PantsS 22.50 30 PantsS 55.99 25 DressesS 15.99 10 SocksC 22.50 10 SocksC 30.15 50 HatsI want to group by the item and calculate a weighted average. No problem. SQL below:SELECT SUM(Price * Quantity) / SUM(Quantity) AS WeightedAverage, ItemFROM MyTableGROUP BY ItemBut what I really want to do is set the weighted average to a specified value if any item in the group is type 'C'. Similar to below which will not work:SELECT CASE WHEN Type = 'C' THEN 22.50 ELSE SUM(Price * Quantity) / SUM(Quantity) END AS WeightedAverage,ItemFROM MyTableGROUP BY ItemThis obviously will not work because Type is not in the group by or aggregate function. There should be a function to accomplish this but there doesn't appear to be. WHY NOT! I'm sure I can figure out other ways to do this but it would make so much sense if there was some kind of aggregate function that did this. I know in the example above I could use MAX but it is not a "clean" solution because it will only work in certain instances. I wish there was a function similar to what I have below (and yes I know "ANY" is already a SQL keyword, but it's the most logical word to use in this instance):SELECT CASE WHEN ANY(Type) = 'C' THEN 22.50 ELSE SUM(Price * Quantity) / SUM(Quantity) END AS WeightedAverage,ItemFROM MyTableGROUP BY ItemMy returned data should look like this:WeightedAverage Item22.50 Socks 4.49 T-Shirts22.50 Hats17.32 Pants55.99 Dresses The data have been disguised to protect the innocent. |
|
|
|
|
|