我使用以下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
语句。
答案 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)