Updating Order field in SQL
We're required to add Ordering to our EventVenue table, which we've done by adding an int field to store the EventVenue's placing in the order. The ordering is based upon the parent Event's ID and the Event's VenueGrouping.
If the VenueGrouping is false the EventVenues will be ordered sequentially. However, if true, the EventVenues for the same Event and derived from the same parent Event will have the same ordering. For example [assuming we've filtered by Event]:
EVID | VenueID | Not Grouped | Grouped
1 | 1 | 1 | 1
2 | 2 | 2 | 2
3 | 2 | 3 | 2
4 | 3 | 4 | 3
The problem is when the grouping is changed. I need some SQL to update the Event's Venue Ordering appropriately but am finding it tricky to get my head round it, especially when going from ungrouped to grouped without leaving gaps.
I'd presume it needs to be in an if statement like below, but if a more efficient/DRY solution is suitable, all the better:
-- Changing from Ungrouped to Grouped
IF @OldGrouping=0 AND @NewGrouping=1
BEGIN
UPDATE EventVenues SET Ordering=...
END
-- Changing from Grouped to Ungrouped
ELSE IF @OldGrouping=1 AND @NewGrouping=0
BEGIN
UPDATE EventVenues SET Ordering=...
END
Any help appreciated.
As requested, more example data: Got annoyed at formatting so used a key for headers: A = EventVenueID, B = VenueID, C = Original Ordering, D = Updated Ordering
Updating from Ungrouped to Grouped
A | B | C | D 101 | 1 | 4 | 3 102 | 2 | 2 | 2 103 | 2 | 3 | 2 104 | 3 | 1 | 1
Updating from Grouped to Ungrouped
A | B | C | D 101 | 1 | 3 | 4 102 | 2 | 2 | 2 103 | 2 | 2 | 3 104 | 3 | 1 | 1
开发者_开发知识库
WITH rows AS
(
SELECT e.*,
ROW_NUMBER() OVER (ORDER BY evid) AS rn,
DENSE_RANK() OVER (ORDER BY venueid) AS dr
FROM EventVenues e
)
UPDATE rows
SET Ungrouped = rn,
Grouped = dr
Update:
If I understand correctly, Ordering
is one column which you update depending on some external parameter (not stored in the DB).
To update from ungrouped to grouped:
WITH rows AS
(
SELECT e.*,
DENSE_RANK() OVER (ORDER BY VenueID DESC) AS dr
FROM EventVenues e
)
UPDATE rows
SET Ordering = dr
This will update the Ordering
in descending VenueID
order, assigning same orders to same VenueID
's
To update from grouped to ungrouped:
WITH rows AS
(
SELECT e.*,
ROW_NUMBER() OVER (ORDER BY evid DESC) AS rn
FROM EventVenues e
)
UPDATE rows
SET Ordering = rn
This will update the Ordering
in descending EVID
order.
精彩评论