SQL Server。新手。不知道如何表达我的问题。尝试通过示例:
对于包含这些字段和值的表:
uniqueV, state, locationcode1, locationcode2, typecode
01, TN, 1, X
02, TN, 1, X
03, TN, 1, Y
04, KY, 2, Z
05, KY, 1, R
06, KY, 1, R
07, KY, 1, R
我需要
的结果01, TN, 1, X, 2 -- e.g. 2 occurrences of 1,X in TN
02, TN, 1, X, 2
03, TN, 1, Y, 1
04, KY, 2, Z, 1
05, KY, 1, R, 3
06, KY, 1, R, 3
07, KY, 1, R, 3
这个新的第5个字段是每个州内[typecode]
对的出现次数
=============================================== =========
请跟进
任何方法都可以生成一个额外的输出列,其中包含状态,位置代码对中特定类型代码的计数。例如,'X'记录的计数
所以
uniqueV, state, locationcode1, locationcode2, typecode
01, TN, 1, X
02, TN, 1, X
03, TN, 1, Y
04, KY, 2, Z
05, KY, 1, R
06, KY, 1, R
07, KY, 1, R
导致
01, TN, 1, X, 2 -- e.g. for TN, 1 there are 2 occurances of 'X' records.
02, TN, 1, X, 2
03, TN, 1, Y, 2
04, KY, 2, Z, 0
05, KY, 1, R, 0
06, KY, 1, R, 0
07, KY, 1, R, 0
我以为我可以自己推断但是错了:(
答案 0 :(得分:4)
我认为你需要这样的东西:
SELECT *,
(
SELECT COUNT(*)
FROM YourTable AS T1
WHERE T1.state = T2.state AND T1.locationcode1 = T2.locationcode1
AND T1.locationcode2 = T2.locationcode2) AS Occur
FROM YourTable AS T2
答案 1 :(得分:1)
我相信这个问题有更有效的解决方案,但我认为现在这可以提供帮助:
EXEC