简体   繁体   中英

Select a group of records based on one record in the group

I seem to be very stuck on a problem. I using Crystal Reports 2008 to pull a list of records from a MS-SQL database. There are two tables involved (they contain order data for subscribers). The first table is OrderMst and the second is OrderDtl. They are joined by two fields, Account and SubNumber. Each Account has many SubNumbers and each SubNumber has many InvoiceNumbers. Each invoice row has a column that tells me wether or not it's the most recent invoice. I need to look at this record to determine whether a customer is active, cancelled, or expired. Then, depending on their status I need to select all the invoices for that SubNumber. I'm stuck trying to figure out a way to do that.

Here's an example:

OrderMst:

Account     SubNumber Pub
72781651    0025      NAVL
72781651    0012      RYIR
72781651    0001      RHCS
80156287    0015      VGFA
80156287    0012      NAVL

OrderDtl:

Account     SubNumber InvoiceNumber PubStatus RenewalThere
72781651    0025      15894578      A         0
72781651    0025      15754897      R         1
72781651    0025      15753412      R         1
72781651    0012      15753357      C         0
72781651    0012      15749875      R         1
72781651    0001      15465874      X         0
72781651    0001      15425789      R         1
80156287    0015      15656738      A         0
80156287    0012      15387956      C         0
80156287    0012      15324568      R         1

So, if I were looking for a count of all the invoices for active subscriptions, I would select {OrderDtl.RenewalThere} = 0 , and my report results would show Account 72781651 SubNumber 0025 has 3 invoices and Account 80156287 SubNumber 0015 has 1 invoice. This is where I'm stuck. I need to use one invoice level record to tell me which subscription I want, and then grab all invoice level records for that invoice. Any ideas?

What you want is a semi-join:

SELECT Account, SubNumber, COUNT(*)
  FROM OrderDtl
 WHERE EXISTS (
   SELECT *
     FROM OrderDtl AS a
    WHERE a.Account = OrderDtl.Account
      AND a.SubNumber = OrderDtl.SubNumber
      AND a.PubStatus = 'A'
      AND a.RenewalThere = 0
)
GROUP BY Account, SubNumber

HTH

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