SitePoint Sponsor

User Tag List

Results 1 to 6 of 6

Thread: Derived query from a Union

  1. #1
    SitePoint Addict lmasi02's Avatar
    Join Date
    Aug 2004
    Location
    Zambia
    Posts
    257
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Derived query from a Union

    Hi All,

    How can i write a query to count the number of records from a derived table. the derived table is a union of two table.

    select msisdn from enrollOffer union DISTINCT select msisdn from enrollHistory
    Power of Knowledge

  2. #2
    From Italy with love bronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    8,607
    Mentioned
    76 Post(s)
    Tagged
    4 Thread(s)
    Code:
    SELECT COUNT(*)
    FROM 
      (SELECT
         msisdn 
       FROM enrollOffer 
       UNION 
       SELECT 
         msisdn 
       FROM enrollHistory
      )
    If you want to count msisdn that are present in both tables as well, use UNION ALL.

  3. #3
    SitePoint Addict lmasi02's Avatar
    Join Date
    Aug 2004
    Location
    Zambia
    Posts
    257
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by guido2004 View Post
    Code:
    SELECT COUNT(*)
    FROM 
      (SELECT
         msisdn 
       FROM enrollOffer 
       UNION 
       SELECT 
         msisdn 
       FROM enrollHistory
      )
    If you want to count msisdn that are present in both tables as well, use UNION ALL.
    I tried this and am getting the error
    ERROR 1248 (42000): Every derived table must have its own alias
    Power of Knowledge

  4. #4
    From Italy with love bronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    8,607
    Mentioned
    76 Post(s)
    Tagged
    4 Thread(s)
    Code:
    SELECT COUNT(*)
    FROM 
      (SELECT
         msisdn 
       FROM enrollOffer 
       UNION 
       SELECT 
         msisdn 
       FROM enrollHistory
      ) AS a
    Ah yes, forgot the alias

  5. #5
    SitePoint Addict lmasi02's Avatar
    Join Date
    Aug 2004
    Location
    Zambia
    Posts
    257
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have tried to put the alian as
    SELECT COUNT(cout) FROM (SELECT msisdn as cout FROM enrollOffer UNION SELECT msisdn as cout FROM enrollHistory );
    but it is all failing. same error message
    Power of Knowledge

  6. #6
    SQL Consultant silver trophybronze trophy
    SitePoint Award Recipient r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    38,463
    Mentioned
    35 Post(s)
    Tagged
    1 Thread(s)
    have a look at exactly where guido put the alias -- compare post #2 and post #4
    r937.com | rudy.ca | Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •