开发者

Can this be accomplished without a subset?

I have a table structure that looks like this:

Columns: Account Number Service Code Quantity

Accounts can have multiple service codes on separate rows. For example, for this account '1868603', their service codes are stored like this:

ACCOUNT_NUMBER  SERVICE_CODE    SERVICE_QUANTITY
1868603     101     1
1868603     101     1
1868603     101     1
1868603     101     1
1868603     101     1
1868603     101     1
1868603     326     1
1868603     326     1
1868603     327     1
1868603     327     1
1868603     328     1
1868603     328     1

I am writing a query which need to see if specific service codes are on their account. I am not concerned ab开发者_运维问答out the quantity. I just want to see if they exist for an account.

This is what I have so far:

SELECT ACCOUNT_NUMBER, COUNT(SERVICE_CODE) HOW_MANY
FROM (
    SELECT DISTINCT ACCOUNT_NUMBER, SERVICE_CODE 
    FROM CUSTOMER_SERVICES
    WHERE   ACCOUNT_NUMBER = 1868603 
        AND     SERVICE_CODE IN('323','326','327','328')
)
GROUP BY ACCOUNT_NUMBER

Which gives me:

ACCOUNT_NUMBER  HOW_MANY
1868603 3

3 is the correct number, because there are three instances of IN('323','326','327','328'), which is what I'm trying to determine.

Is there a way to simplify this query without subsetting the data first?

Thanks!


Can ORACLE do COUNT(DISTINCT <field>)?

SELECT
  ACCOUNT_NUMBER, COUNT(DISTINCT SERVICE_CODE) HOW_MANY
FROM
  CUSTOMER_SERVICES
WHERE
  ACCOUNT_NUMBER = 1868603 
  AND SERVICE_CODE IN('323','326','327','328')
GROUP BY
  ACCOUNT_NUMBER


Also, note that having sub-querys does not always imply poor performance. SQL is a language for expressing the logic, but it is compiled and executed in a way you may not feel resembles the SQL very closely.

As such windowing functions (like DENSE_RANK) may also have different performance charactertics worthy of a try...

SELECT
  account_number,
  MAX(rank_id)
FROM
(
  SELECT
    account_number,
    DENSE_RANK() OVER (PARTITION BY account_number ORDER BY service_code) AS rank_id
  FROM
    customer_services
  WHERE
    account_number = 1868603 
    AND service_code IN('323','326','327','328')
)
  AS Data
GROUP BY
  account_number


Yes:

SELECT ACCOUNT_NUMBER, COUNT(DISTINCT SERVICE_CODE) HOW_MANY
FROM CUSTOMER_SERVICES
WHERE   ACCOUNT_NUMBER = 1868603 
AND     SERVICE_CODE IN('323','326','327','328')
GROUP BY ACCOUNT_NUMBER
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜