Note that there are some explanatory texts on larger screens.

plurals
  1. PODetermine most recent 'vote type' for a record, returning 2 fields for HasVotedUp/Down?
    primarykey
    data
    text
    <p>I have a SQL Server 2008 table containing 'votes'. They are either a 'VoteUp' or 'VoteDown' <code>VoteTypeId</code> (1 or 2 respectively).</p> <p>Each vote has a timestamp of when the vote was inserted in the table.<br> Each vote row belongs to a post (FK <code>PostId</code>).<br> Each vote row belongs to a user (FK <code>UserId</code>).</p> <p>I have a query to bring back a list of posts, and in that same query, I want to identify if the current user has voted that post up or down (or not at all).</p> <p>In some cases, a single post may contain both an Up AND a Down vote, where the user changed their mind at a later date (changing a Down vote to an Up vote). In this scenario, I want to identify the latest vote as being the relevant vote (the original down vote is simply held in the DB for historic purposes).</p> <p>Ideally, I'd like 2 simple BIT fields returned within the Query: <code>HasVotedUp</code> and <code>HasVotedDown</code>.</p> <p>I <em>could</em> include something like this (cut down for brevity), to simply return whether the most recent vote for that user/post is an Up or Down vote, then assign the 'HasVotedUp' and 'HasVotedDown' properties in code based on the returned VoteTypeId...</p> <pre><code>select p.id, p.body, (select top 1 votetypeid from votes where userid = 1 and postid = p.id order by creationdate desc) as CurrentVoteTypeId from posts p </code></pre> <p>... but I wondered if there was a similarly simple (but importantly, efficient) approach that I could use to return the 2 'HasVotedUp/Down' fields within the query, so it's on a plate, ready to use?</p> <p>This nested approach was all I came up with so far but I'm sure this is inefficient?!</p> <pre><code>select cast((select count(1) from votes where userid = 1 and postid = p.id and votetypeid = 1 and creationdate &gt; (select creationdate from votes where userid = 1 and postid = p.id and votetypeid = 2)) as bit) as HasVotedUp, cast((select count(1) from votes where userid = 1 and postid = p.id and votetypeid = 2 and creationdate &gt; (select creationdate from votes where userid = 1 and postid = p.id and votetypeid = 1)) as bit) as HasVotedDown from posts p </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload