Column is invalid in select

前端 未结 4 1682
囚心锁ツ
囚心锁ツ 2021-01-26 10:51

How I will properly do this:

Customer

CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd

Order

OrderID,  Ord         


        
相关标签:
4条回答
  • 2021-01-26 11:31

    A little bit different version (from that Gordon Linoff suggests):

    select
         cnt, c.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
    from Customer c 
    join (
        select  
            count(OrderID) cnt, CusID
        from Order o 
        group by
            CusID
    ) o on
        c.CusID = o.CusID
    order by
        c.CusID // ordering by OrderID and Order is out of logic :)
    
    0 讨论(0)
  • 2021-01-26 11:51

    Why do I need to add those columns in the Group By Clause?

    Because you are saying you need to group the results and give one result per ID. This leaves you with two choices.

    1) Getting the count with all details at the customer level, which is what you would want in your example.

    Select  Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
    From Customer c 
    Inner join
    Order o
    On c.CusID = o.CusID
    Group By o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd;
    

    2) Or in case the other columns are some numbers (say salaries in a department) or so, every column not in the group by should have an aggregate function.

    select dept_id, sum(salary), max(salary), min(salary)
    from dept
    group by dept_id;
    

    When you want one row per your grouped column, you need to specify how to aggregate the other columns.

    0 讨论(0)
  • 2021-01-26 11:52

    I also find first answer to be the best, but in SQL2005 CTEs came into existence and they can help obtain better readability:

    ;with order_cte as (
        select count(OrderID) cnt, CusID
        from Order o 
        group by CusID
    )
    select cnt, c.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
    from Customer c 
       join order_cte o on c.CusID = o.CusID
    order by c.CusID
    
    0 讨论(0)
  • 2021-01-26 11:55

    Just include them in the group by clause:

    Select  Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
    From Customer c 
    Inner join
    Order o
    On c.CusID = o.CusID
    Group By o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd;
    
    0 讨论(0)
提交回复
热议问题