SQL Server:获取每个人的最大购买价值

时间:2018-05-15 21:03:16

标签: sql-server max

我有以下查询

select 
    C.Persona, C.Producto, Sum(C.Cantidad * P.Precio) [Total_Purchase]
from
    Compras C 
join
    Precios P on C.Producto = P.Item
group by 
    C.Producto, C.Persona

返回每个产品的每个客户(Persona)的总购买量。 如何才能为每位客户和所涉及的产品带来Max Total Purchase?

3 个答案:

答案 0 :(得分:0)

您可以使用MAX()功能执行此操作。您可以将其添加到您的选择中,即使使用SUM()也可以使用。

MAX() Examples

答案 1 :(得分:0)

试试这个:

select 
     max(c.[Total_Purchase]), C.Producto ,C.Persona
from 
    (select 
         C.Persona, C.Producto, Sum(C.Cantidad*P.Precio) [Total_Purchase]
     from
         Compras C 
     join
          Precios P on C.Producto = P.Item
     group by 
         C.Producto, C.Persona) c
 group by 
     C.Producto, C.Persona

答案 2 :(得分:0)

将SUM聚合更改为MAX 或者包括两者

package com.company.appname.util;
import android.content.Context;
import com.company.appname.Constants;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;
import okhttp3.CookieJar;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public class RetrofitAdapter {
    public static OkHttpClient okHttpClient;
    public static Context context;

public static RetrofitInterface getRetroInterface(String endPoint){
    return createRestAdapter(endPoint).create(RetrofitInterface.class);
}

public static Retrofit createRestAdapter(String endPoint){
    boolean isMobileAPI = false;

    //Check if the endpoint is the mobile api
    if(endPoint.equalsIgnoreCase(Constants.MOBILE_SERVICE_BASE_URI)){
        isMobileAPI = true;
    }

    //Create a rest adapter
    return  new Retrofit.Builder()
            .client(createOkClient(isMobileAPI))
            .baseUrl(endPoint)
            .addConverterFactory(JacksonConverterFactory.create())
            .build();
}

public static OkHttpClient createOkClient(boolean isMobileAPI){

    NextModel next = NextModel.getInstance();

    if(next.okClient == null || !isMobileAPI) {
        //Create ok http Client
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        //Set timeouts
        httpClient.readTimeout(Constants.TIMEOUT, TimeUnit.MILLISECONDS);
        httpClient.connectTimeout(Constants.TIMEOUT, TimeUnit.MILLISECONDS);

        CookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));

        //Add cookieJar to Http Client
        httpClient.cookieJar(cookieJar);

        //Create OkHttpClient
        okHttpClient = httpClient.build();

        return okHttpClient;
    }else{
        //Return already created okclient
        return next.okClient;
    }
}


public static OkHttpClient getOkClient() {
    return okHttpClient;
}

}