MySQL GROUP BY doesn't work when migrated to SQL Server 2012

前端 未结 3 1669
执笔经年
执笔经年 2021-01-23 06:08

I\'m moving my Delphi application from MySQL to SQL server 2012. In MySQL I had this query:

SELECT *,(XS+S+M+L+XL+XXL+[1Size]+Custom) as Total FROM StockData  
G         


        
相关标签:
3条回答
  • 2021-01-23 06:50

    You can also use this approach:

    with OrdinalOnGroup
    (
        SELECT 
            Ordinal = rank() over(partition by StyleNr, Customer, Color order by id) 
            , *, (XS+S+M+L+XL+XXL+[1Size]+Custom) as Total 
        FROM StockData  
    )
    select * 
    from OrdinalOnGroup
    where Ordinal = 1;
    

    PARTITION BY denotes the grouping of related information, this is called windowing

    0 讨论(0)
  • 2021-01-23 06:52

    All columns in an aggregate query must either be used by an aggregate function or a group by. Try only selecting the columns you require rather than * I.e. select stylenr, customer, color, ([...] ) as Total from.

    This is a SQL standard way of dealing with aggregates, you'd get a similar error in Oracle.

    0 讨论(0)
  • 2021-01-23 06:54

    SQL Server is working as expected. You must include all items in your SELECT list in either a GROUP BY or in an aggregate function:

    SELECT *,(XS+S+M+L+XL+XXL+[1Size]+Custom) as Total 
    FROM StockData  
    -- GROUP BY ID,StyleNr,Customer,Color, XS,S,M,L,XL,XXL,[1Size],Custom
    ORDER BY StyleNr,Customer,Color
    

    Or you might be able to use:

    SELECT StyleNr,Customer,Color, SUM(XS+S+M+L+XL+XXL+[1Size]+Custom) as Total 
    FROM StockData  
    GROUP BY StyleNr,Customer,Color
    ORDER BY StyleNr,Customer,Color;
    
    0 讨论(0)
提交回复
热议问题