Question

I have the following table with three columns:

tb1

userID   itemID   rating

This table contains information about the ratings given by users to different items. A user can give ratings to multiple items, and an item can receive ratings from multiple users.

I need to update the rating values for this table, so that half the items in tb1 should be assigned 5 rating and other half should be assigned 1 rating.

Note: This means that while a user can give different ratings to different items, an item can have either all its ratings as 1 or all ratings as 5.

Initially, the rating values are NULL for all pairs of users and items.

This task could be performed using two separate queries.

 UPDATE tb1
    SET rating = 5 
  WHERE itemID IN 
        (SELECT top(50) percent itemID
           FROM tb1 
          GROUP BY itemID
          ORDER BY newid());

 UPDATE tb1
    SET rating = 1
  WHERE rating IS NULL

Is there a way to combine both these queries into a single query?

Was it helpful?

Solution

You don't state if it matters if the first half are 1 and the second half are 5s only that 50% should be each.

If it doesn't matter then you can do something like this:

 UPDATE tb1
    SET rating =
        (CASE
             WHEN itemId <=
                  (SELECT MAX(itemID)
                     FROM 
                          (SELECT TOP (50) percent itemID
                             FROM tb1 
                            GROUP BY itemID
                            ORDER BY itemID
                          ) x
                  ) THEN 5
             ELSE 1
         END)

Or if your records don't have any deleted items or you're not strictly concerned about being exactly 50% then you could simply do something like this:

 UPDATE tb1
    SET rating = CASE
                     WHEN (itemID % 2) = 1 THEN 1
                     ELSE 5
                  END

the benefit of this approach is you can do things like this:

UPDATE tb1
   SET rating = 
       CASE (itemID % 5) 
            WHEN 1 THEN 1
            WHEN 2 THEN 7
            WHEN 3 THEN 10
            WHEN 4 THEN 40
            ELSE 5
        END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top