【问题标题】:Grouping Output Data After Having Statement有语句后对输出数据进行分组
【发布时间】:2018-05-31 17:05:46
【问题描述】:

我正在使用 Microsoft SQL Server 2012 并坚持使用 SQL 编码。

我有以下几列 Year、Month 和 Active,下面是一些小样本数据:

Year Month Active
2005  Feb     Y
2005  May     Y
2006  Nov     Y
2007  Jul     Y
2008  Jan     Y
2008  Mar     Y

我想恢复一年内有 2 个或更多“活跃”月份(HAVING Active > 2)的年份。因此,从这些数据中,我想带回年份:2005 年和 2008 年。

我希望数据像这样读取:

Year   Month
2005  Feb, May
2008  Jan, Mar

我该怎么做?我知道如何分组和使用 Count 函数,但我知道有更好的方法让数据看起来像上面那样。我需要在 1 个查询中完成所有这些操作。

任何帮助/建议将不胜感激。

【问题讨论】:

    标签: sql sql-server grouping having-clause


    【解决方案1】:

    您可以将cte窗口 功能一起使用:

    with cte as ( 
          select *
          from (select *, count(*) over (partition by year) c
                from table 
               ) t
          where c > 1
    )
    select Year,
           stuff( (select ','+Month
                   from cte c1
                   where c.year = c1.year 
                   for xml path('')
                  ), 1, 1, ''
                ) as Month
    from cte c
    group by Year;   
    

    上述查询使用xml 方法和stuff() 函数将行抓取到单个字段中。但是,如果您有任何升级 SQL Server 的计划,那么您将通过STRING_AGG() 函数而不是xml + stuff() 获得非常短的方法。

    【讨论】:

      【解决方案2】:

      您可以通过并在派生表中进行分组。这将为您提供具有多个活动月份的年份。然后,您可以使用子查询从表中获取与派生表中年份相同的月份。 FOR XML PATH('') 会将值转换为逗号分隔的字符串,而 STUFF 只会删除前导逗号和空格。

      select  Year, 
              stuff((select ', ' + Month
                     from     Table1 t1
                     where    t1.Year = dt.Year 
                     for xml path(''))
                     ,1,2,'') as Month
      From    (
                  select      Year 
                  from        Table1 
                  where       Active = 'Y'
                  group by    Year
                  having      count(*) > 1
              ) dt
      

      【讨论】:

        【解决方案3】:

        试试这个:

        select Year,
               stuff( (select ','+Month
                       from YourTable c1
                       where c.year = c1.year 
                       for xml path('')
                      ), 1, 1, ''
                    ) as Month
        from YourTable c
        group by Year
        Having SUM(CASE WHEN Active='Y' THEN 1 Else 0 END)>=2; 
        

        【讨论】:

        • #tab1 YourTable?
        • 这是一个错误。已更正
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-22
        • 2021-07-09
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多