在另一个查询中引入新创建的计算列

时间:2015-10-06 17:37:15

标签: sql-server-2005 subquery left-join case calculated-columns

我在下面有两个单独的查询,它们运行正常。现在我已经创建了一个计算列来提供YM的工作日计数,并希望将其传递给query1(连接将是query1.Period = query2。 YMS) 请参阅下面的查询和输出。

SELECT        Client, ClientGroup, Type, Value, Period, PeriodName, PeriodNumber, ClientName
FROM            metrics.dbo.vw_KPI_001_Invoice 



select YMs,sum(case when IsWorkDay = 'X' then 1 else 0 end) from IESAONLINE.Dbo.DS_Dates
where Year > '2013'
group by YMs 

Query 1
Client  ClientGroup Type    Value   Period  PeriodName        PeriodNumber   ClientName
0LG0    KarroFoods  Stock   5691.68 201506  Week 06 2015    35  Karro Foods Scunthorpe

Query 2
YMs (No column name)
201401  23

1 个答案:

答案 0 :(得分:0)

以下工作如何:

SELECT Client, ClientGroup, Type, Value, Period, PeriodName, PeriodNumber, ClientName, cnt
FROM            metrics.dbo.vw_KPI_001_Invoice q1
INNER JOIN (select YMs,sum(case when IsWorkDay = 'X' then 1 else 0 end) as cnt from IESAONLINE.Dbo.DS_Dates
where Year > '2013'
group by YMs ) q2 ON q1.Period = q2.YMs

如果值不总是可用,那么您可以考虑将INNER JOIN更改为OUTER JOIN。