【问题标题】:Can get the Union to work correctly可以让联盟正常工作
【发布时间】:2014-06-10 14:06:12
【问题描述】:
   Select CorpID,
    Convert(VarChar(2),Month(E.BeginDate)) + '/' + Convert(VarChar(4),Year(E.BeginDate)),
    Count(Year(e.BeginDate)) As 'total Screen'
    --Count(Month(E.CurrentBeginDate))
    From dbo.NonCalls E
    Where E.BeginDate between {d'2013-01-01'} and {d'2013-12-31'}
    Group By CorpID, Year(E.BeginDate),Month(E.BeginDate)

    Union ALL


    Select CorpID,
    Convert(VarChar(2),Month(E.CurrentBeginDate)) + '/' + Convert(VarChar(4),Year(E.CurrentBeginDate)),
    Count(Year(e.CurrentBeginDate)) As 'total Screen'
    --Count(Month(E.CurrentBeginDate))
    From dbo.Employee E
    Where E.CurrentBeginDate between {d'2013-01-01'} and {d'2013-12-31'}
    Group By CorpID, Year(E.CurrentBeginDate),Month(E.CurrentBeginDate)
    --Order By CorpID, Year(E.CurrentBeginDate), Month(E.CurrentBeginDate)                                                                                                                  

我将我的代码更改为这个,现在我得到了我正在寻找的数字,唯一的问题是它没有排序我需要它按 Corpid 排序,然后按日期 01-02-03 等我不太确定

how to get that accomplish any help would be greatly apreciated. 

【问题讨论】:

  • 错误信息是?你用的是什么数据库?
  • Msg 205,级别 16,状态 1,行 1 所有使用 UNION、INTERSECT 或 EXCEPT 运算符组合的查询必须在其目标列表中具有相同数量的表达式。数据库是 SQL
  • @user3571281 - “SQL” 不是数据库,它是多个数据库实现的标准化语言。这就像去杂货店看冰淇淋——Dreyer's 有香草味,Costco、Haagen Daz、Ben & Jerry's 等也有。哦,它们都有微妙的不同。不要包含注释掉的代码 - 它不应该运行并且只会混淆事物,因此不会带来好处。 (从您的查询中消除它也会导致它运行吗?)。您的查询似乎不会以会引发给定错误的方式无效。

标签: sql sql-server


【解决方案1】:

您在 UNION 的第二部分中有 2 个 CurrentBeginDate,导致该部分返回 5 列,但第一部分只有 4 列

SELECT    
 CorpID ,
 CurrentBeginDate <--HERE,
 CONVERT(VARCHAR(2), MONTH(E.CurrentBeginDate)) + '/'
           + CONVERT(VARCHAR(4), YEAR(E.CurrentBeginDate)) AS CurrentBeginDate <--HERE,
 COUNT(YEAR(e.CurrentBeginDate)) AS 'total Screen' ,
 '' AS d1

正如错误消息所说,要使联合工作,它需要从查询的所有部分返回相同数量的列。

【讨论】:

    【解决方案2】:

    作为对“关于对现在正确合并的数据进行排序的新问题”的回答:

    您需要将联合结果集视为派生表,并根据您的订单从中进行选择。由。

    SELECT * 
      FROM (<your unioned query)
     ORDER BY CorpID
          ,Year(CurrentBeginDate)
          ,Month(CurrentBeginDate)      
    

    更完整的讨论请参见此处: TSQL ORDER-BY with a UNION of disparate datasets

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多