Results 1 to 5 of 5

Thread: SQL query help

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2005
    Posts
    69

    SQL query help

    I have 2 tables

    JOBS

    JOBNO HRSWORKED
    111 12
    111 1
    111 3

    222 4
    222 6

    JOBLT

    JOBNO BUDGETEDHRS
    111 20
    222 10

    SELECT JOBNO, BUDGETEDHRS, (SELECT SUM (HRSWORKED) FROM JOBS WHERE JOBS.JOBNO= JOBLT.JOBNO GROUP BY JOBS.JOBNO ) AS TOTALHRSWORKED , (TOTALHRSWORKED-BUDGETEDHRS) AS OVERBUDGET
    FROM JOBLT ORDER BY JOBNO

    Here I am getting the error TOTALHRSWORKED as invalid column

    How can I fix that?
    thx

  2. #2
    Fanatic Member space_monkey's Avatar
    Join Date
    Apr 2005
    Location
    神と歩くこと
    Posts
    573

    Re: SQL query help

    I'm pretty sure you can't refer to an aliased column like you would a column name.

    But i will be interested to see if someone else has a suggestion on how to do this kind of thing.
    Using VB6 or VB.net 2008 with .net 3.5
    "Life... death... either way I'll be confined to a small cubicle!" - Hermes Conrad

  3. #3
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: SQL query help

    Code:
    SELECT JOBNO
       , BUDGETEDHRS
       , (SELECT SUM (HRSWORKED) FROM JOBS WHERE JOBS.JOBNO= 
              JOBLT.JOBNO GROUP BY JOBS.JOBNO ) AS TOTALHRSWORKED
       , ((SELECT SUM (HRSWORKED) FROM JOBS WHERE JOBS.JOBNO= 
              JOBLT.JOBNO GROUP BY JOBS.JOBNO ) -BUDGETEDHRS) AS OVERBUDGET 
    FROM JOBLT ORDER BY JOBNO
    Simply repeat the sub-query in the other column - it won't run it "twice" if it's MS SQL SERVER (not sure of other DB's query optimizers)...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  4. #4
    Fanatic Member space_monkey's Avatar
    Join Date
    Apr 2005
    Location
    神と歩くこと
    Posts
    573

    Re: SQL query help

    Yeah i was worried that it would run it twice.
    Using VB6 or VB.net 2008 with .net 3.5
    "Life... death... either way I'll be confined to a small cubicle!" - Hermes Conrad

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Jul 2005
    Posts
    69

    Re: SQL query help

    Thanks.

Posting Permissions

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



Click Here to Expand Forum to Full Width