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.
答案 0 :(得分:2)
你在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
正如错误消息所示,要使联合起作用,它需要从查询的所有部分返回相同数量的列。
答案 1 :(得分:0)
作为对“关于对现在正确联合的数据进行排序的新问题的答案:
您需要将unioned结果集视为派生表,并使用您的订单从中进行选择。由
SELECT *
FROM (<your unioned query)
ORDER BY CorpID
,Year(CurrentBeginDate)
,Month(CurrentBeginDate)
有关更完整的讨论,请参阅此处: TSQL ORDER-BY with a UNION of disparate datasets