显示 SQL select 以及自身的计数?

show a SQL select along with a count of itself?

(注意:新手警告) 我必须将生成的视图的子部分与视图本身一起计算。

可能吗?

例如,这是从 SQL select:

生成的视图
Client Type      Year
8963   Rural     2012
9044   City      2013
8963   Rural     2014
5145   Rural     2014
5145   City      2012

我要显示的是:

Client Type      Year  CountofRural2012 CountofCity2012 CountofRural2013
8963   Rural     2012  1                   1                  0
9044   City      2013
8963   Rural     2014
5145   Rural     2014
5145   City      2012

...所有计数排列依此类推。

查看 Subqueries and the Count 函数。您可以将一个查询包装在另一个查询中,并使用聚合对结果进行计数、求和甚至标准偏差。

首先,我建议您研究一下 pivot 等函数。

https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/pivoting_tables56?lang=en

其次,如果你要创建的字段是事先知道的(也就是说,你想为特定年份创建字段),你可以尝试sum/count一个案例字段。

Select client, type, year,
       sum(case when type='Rural' and year=2012 then 1 else 0 end) countOfRural2012
from YOUR_TABLE
Group by client, type, year

阿迪亚

这里是不创建新的 table

的方法
select [Client], [Type], [Year],
(Select COUNT([Year]) From PTable  where [Year] = 2012 and [Type] = 'Rural') [CountofRural2012],
(Select COUNT([Year]) From PTable  where [Year] = 2012 and [Type] = 'City') [CountofCity2012],
(Select COUNT([Year]) From PTable  where [Year] = 2013 and [Type] = 'Rural')[CountofRural2013]
from PTable

这是现场演示https://data.stackexchange.com/Whosebug/query/397150

希望对您有所帮助。

在你运行上面的查询

之后像这样手动更新
  Update PTable Set [CountofRural2012] = '' where Client <> 8963
  Update PTable Set [CountofCity2012] = '' where Client <> 8963
  Update PTable Set [CountofRural2013] = '' where Client <> 8963