Skip to content
Advertisement

Getting count depending on subquery

In my SELECT statement below, I’m looking to get a COUNT of connections from a table, where connections are defined as 1 connection per unique transactionID.
Thus, in my COUNT, I want to check to make sure that a connection has not already been made (i.e. same transactionID but a lower primary key id).

I tried using COUNT(DISTINCT pc.TransactionID) but the problem was that the same transactionID can occur within each grouping (ThisDate, SiteName, UserName, Command), so it was counting some connections more than once.

Then I tried joining with the same table and used SUM instead of COUNT, which seemed to work, but that increased BytesTransferred value due to the extra records that were pulled in.

Ideas on the best way to handle this?

ProtocolCommands table

Select statement

To give an example, here are some records:

When executing the SELECT with the COUNT(DISTINCT pc.TransactionID) and removing the inner join, the results are this (note incorrect DataTransferred for the last two rows):

When executing the SELECT with the SUM and adding the inner join, the results are this (note incorrect Connections – there should only be 1 total):

Expected result:

Advertisement

Answer

Not sure if I understood correctly, but you seem to want to detect the oldest occurance of a connection. You can do that using this query:

This will have RowNum = 1 for the record where connection appears for the very first time.

Joining that to your main table you can get the correct connection count

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement