简体   繁体   中英

sql query returning number of rows from joined table

So I have this:

    const string sqlString =
        "SELECT * FROM Causes c INNER JOIN CauseMembers m ON " +
        "(c.Id = m.CauseId) AND (UserName = @UserName) " +
        "ORDER BY c.DateTime DESC;";

Works fine, however I'd like to return a generated column containing the number of rows returned from this query from the table causemembers. So that I can get the actual members who joined this 'cause' (from Causes).

Your inputs? Thanks

Since you are already returning all columns (*) and you have tagged C#, it looks like you are loading the result into a DTO (or ADO.NET object).

Why don't you just count the number of rows/items in the resulting object?

If you're using SQL Server 2005 or higher, then you can use a window function:

SELECT <ALL COLUMNS YOU'RE INTERESTED IN>, COUNT(m.CauseId) OVER (PARTITION BY c.ID)
FROM Causes c JOIN CauseMembers m ON (c.Id = m.CauseId) AND (UserName = @UserName)
ORDER BY c.DateTime DESC

This will get you a count of the number of rows returned per cause ID. If you want to ensure that every cause is returned, whether any members belong to it or not, then change the JOIN to a LEFT OUTER JOIN . If there are no CauseMembers, then the NULL from the outer join will not be counted, so you'll get zero.

this will get you the counts, but not the other fields. The other method would be to use an embedded select statement using

const string sqlString =
"SELECT c.ID, COUNT(m.causeID) FROM Causes c RIGHT OUTER JOIN CauseMembers m ON " +
"(c.Id = m.CauseId) AND (UserName = @UserName) " +
"GROUP by c.ID ;";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM