Verhogen
Verhogen

Reputation: 28611

SQL use GROUP BY such that it results in the original SELECT

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

Upvotes: 0

Views: 206

Answers (4)

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340241

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?

Upvotes: 5

gbn
gbn

Reputation: 432261

...GROUP BY NEWID()

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

Upvotes: 1

Tzury Bar Yochay
Tzury Bar Yochay

Reputation: 9004

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

Upvotes: 0

Corey Ballou
Corey Ballou

Reputation: 43457

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;
}

Upvotes: 0

Related Questions