tags:

views:

80

answers:

4

I have a SQL query that is something like

SELECT SUM(price) FROM budget GROUP BY {{PLACEHOLDER}}

where {{PLACEHOLDER}} will be replaced in the code. Is it possible to replace it by something that will result in the same output as the following statement?

SELECT price FROM budget
+5  A: 

If you have a unique column, like an autogenerated id you can use that

SELECT SUM(price) FROM budget GROUP BY budget_id

will be equal to

SELECT price FROM budget

if every row has a different budget_id (identity, autoincrement fields will fit the bill)

Now, I urge you to reconsider the wisdom of doing such a hack, why don't you put an if where it matters?

Vinko Vrsalovic
ROW_ID() on SQL Server? Not in any version I've worked on, If you mean ROW_NUMBER(), you won't be able to aggregate on it without a CTE or derived table. However, you are correct about grouping on the key column
gbn
Thanks gbn, got confused by Tzury's answer
Vinko Vrsalovic
A: 

My recommendation is to include GROUP BY directly in your placeholder if and only if a placeholder exists:

if (!empty($placeholder)) {
    $placeholder = 'GROUP BY ' . $placeholder;
}
cballou
A: 

If I understood you correctly, you wish to omit the group by effective. In that case, make it GROUP BY ROW_ID This will yield the same results

Tzury Bar Yochay
You are assuming the poster uses SQL Server, no such guarantee in the question (so far.)
Vinko Vrsalovic
@Vinko: ROW_ID() is not in SQL Server...
gbn
Well, it's still assuming a rdbms version. My mistake though. (And Tzury's)
Vinko Vrsalovic
tagged as SQL. That usually related to RDBMS ASAIK
Tzury Bar Yochay
Yes, but not to SQL Server (or whatever engine supports ROW_ID) or you meant a unique id?
Vinko Vrsalovic
that was just a name for the field holding the primary_key/row_id/unique_id whatever you prefer to call it.
Tzury Bar Yochay
+1  A: 
...GROUP BY NEWID()

Random per row, so never aggregates. And separate to key column(s), schema etc

gbn
What if you are unlucky (and get the same id twice)? Or is that guaranteed to return differently for each row on a single query? It's also RDMB specific
Vinko Vrsalovic
It's a GUID: the chances of collision are astronomical.
gbn
Great. Still RDBMS specific I meant up there.
Vinko Vrsalovic