SQL Query获取每年的最小和最大日期日期范围

时间:2015-09-08 08:26:59

标签: sql sql-server sql-server-2008

目前我有一个查询,它正在加载给定租户的每年销售额。使用下面的代码,我可以产生这个结果(见图表)

SELECT DATENAME(month,date) [month]
    ,ISNULL(SUM(CASE WHEN YEAR (DATE) = @Year1 THEN gsc END), 0) AS 'Year1'
    ,ISNULL(SUM(CASE WHEN YEAR (DATE) = @Year2 THEN gsc END), 0) AS 'Year2'
    ,ISNULL(SUM(CASE WHEN YEAR (DATE) = @Year3 THEN gsc END), 0) AS 'Year3'
    ,ISNULL(SUM(CASE WHEN YEAR (DATE) = @Year4 THEN gsc END), 0) AS 'Year4'
    ,ISNULL(SUM(CASE WHEN YEAR (DATE) = @Year5 THEN gsc END), 0) AS 'Year5'
INTO #LRSalesAnalysis
FROM dailymod 
WHERE tenantcode = @RP 
GROUP BY DATENAME(month,date)
ORDER BY DATEPART(MM,DATENAME(month,date)+' 01 2011')

部分代码,请注意参数@ Year1-5的值类似于(2011,2012等)

结果

enter image description here

我现在想要的是获得每年的最短日期和最长日期。导致像这样的东西

enter image description here

源数据库实际上是每个日期的销售集合。所以我想获得在给定日期范围(年)中找到的最大和最小日期

非常感谢任何帮助

1 个答案:

答案 0 :(得分:4)

这是使用您已经使用的相同技术完成的。只有两个查询,一个用于min,一个用于max,您将与UNION ALL粘合在一起。

SELECT 
  'Min Date' AS what
  ,MIN(CASE WHEN YEAR(DATE) = @Year1 THEN DATE END) AS 'Year1'
  ,MIN(CASE WHEN YEAR(DATE) = @Year2 THEN DATE END) AS 'Year2'
  ,MIN(CASE WHEN YEAR(DATE) = @Year3 THEN DATE END) AS 'Year3'
  ,MIN(CASE WHEN YEAR(DATE) = @Year4 THEN DATE END) AS 'Year4'
  ,MIN(CASE WHEN YEAR(DATE) = @Year5 THEN DATE END) AS 'Year5'
FROM dailymod 
WHERE tenantcode = @RP 
UNION ALL
SELECT
  'Max Date' AS what
  ,MAX(CASE WHEN YEAR(DATE) = @Year1 THEN DATE END) AS 'Year1'
  ,MAX(CASE WHEN YEAR(DATE) = @Year2 THEN DATE END) AS 'Year2'
  ,MAX(CASE WHEN YEAR(DATE) = @Year3 THEN DATE END) AS 'Year3'
  ,MAX(CASE WHEN YEAR(DATE) = @Year4 THEN DATE END) AS 'Year4'
  ,MAX(CASE WHEN YEAR(DATE) = @Year5 THEN DATE END) AS 'Year5'
FROM dailymod 
WHERE tenantcode = @RP;