将代码转换为从多个字段获得平均值以从多个字段获取MAX的简单方法

时间:2017-10-27 11:19:15

标签: sql-server tsql

我使用以下sql来获取三个地区一周中每一天的总销售额:

SELECT 
    SUM(CASE WHEN DATEPART(weekday, [the_date]) NOT IN (1,3,4,5,6,7) THEN  [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Monday_SUM_sales],
    SUM(CASE WHEN DATEPART(weekday, [the_date]) NOT IN (1,2,4,5,6,7) THEN  [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Tuesday_SUM_sales],
    SUM(CASE WHEN DATEPART(weekday, [the_date]) NOT IN (1,2,3,5,6,7) THEN  [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Wednesday_SUM_sales],
    SUM(CASE WHEN DATEPART(weekday, [the_date]) NOT IN (1,2,3,4,6,7) THEN  [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Thursday_SUM_sales],
    SUM(CASE WHEN DATEPART(weekday, [the_date]) NOT IN (1,2,3,4,5,7) THEN  [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Friday_SUM_sales],
    SUM(CASE WHEN DATEPART(weekday, [the_date]) NOT IN (1,2,3,4,5,6) THEN  [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Saturday_SUM_sales],
    SUM(CASE WHEN DATEPART(weekday, [the_date]) NOT IN (2,3,4,5,6,7) THEN  [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Sunday_SUM_sales],
    USAsalesmanager,
    UKsalesmanager,
    ASIAsalesmanager
FROM 
    WORLDSALESDATA 
GROUP BY 
    GROUPING SETS(USAsalesmanager, UKsalesmanager, ASIAsalesmanager)

是否有一种简单的方法可以将此代码转换为获取一周中每一天的销售总价值,以及获取一周中每一天的MAX值?我尽量保持sql query尽可能短,如果可能的话,不要使用多个IF语句。

1 个答案:

答案 0 :(得分:2)

您会使用MAX(),但我不确定您使用IN代替=的原因:

SELECT MAX(CASE WHEN DATEPART(weekday, [the_date]) = 2 THEN [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Monday_SUM_sales],
       MAX(CASE WHEN DATEPART(weekday, [the_date]) = 3 THEN [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Tuesday_SUM_sales],
       MAX(CASE WHEN DATEPART(weekday, [the_date]) = 4 THEN [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Wednesday_SUM_sales],
       MAX(CASE WHEN DATEPART(weekday, [the_date]) = 5 THEN [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Thursday_SUM_sales],
       MAX(CASE WHEN DATEPART(weekday, [the_date]) = 6 THEN [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Friday_SUM_sales],
       MAX(CASE WHEN DATEPART(weekday, [the_date]) = 7 THEN [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Saturday_SUM_sales],
       MAX(CASE WHEN DATEPART(weekday, [the_date]) = 1 THEN [USA_SALES]+[UK_SALES]+[ASIA_SALES] END) as [Sunday_SUM_sales],
       USAsalesmanager, UKsalesmanager, ASIAsalesmanager
FROM WORLDSALESDATA 
GROUP BY GROUPING SETS(USAsalesmanager, UKsalesmanager, ASIAsalesmanager)