4

我有table A五行和以下值:

Column1  Column2  Column3  Column4
-------  -------  -------  -------
anna     ben      cat      d
anna     ben      cat      e
anna     ben      cat      f
gina     hugh     ken      m
gina     hugh     ken      p

我想添加另一个名为Column5. Column 5前 3 行的值为3,接下来的 2 行为 2:

Column1  Column2  Column3  Column4  Column5
-------  -------  -------  -------  -------
anna     ben      cat      d        3
anna     ben      cat      e        3
anna     ben      cat      f        3
gina     hugh     ken      m        2
gina     hugh     ken      p        2

我是怎么做到的:

SELECT DISTINCT COUNT (DISTINCT t1.Column4) AS Column5,
Column1, Column2, Column3, Column4
FROM TableA AS t1
GROUP BY Column1, Column2, Column3;

这不起作用:

消息 8120,级别 16,状态 1,过程 COUNT,第 29
行列 'Column4' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

请问有什么帮助吗?非常感激。

PS:如果我Column4在 group by 子句中添加,我在结果表中只得到“1”的值Column5

4

5 回答 5

4

另一种方法是先选择不同的行,然后应用窗口化的 COUNT() 函数:

WITH distinctrows AS (
  SELECT DISTINCT
    Column1,
    Column2,
    Column3,
    Column4
  FROM TableA
)
SELECT
  Column1,
  Column2,
  Column3,
  Column4,
  COUNT(Column4) OVER (PARTITION BY Column1, Column2, Column3) AS Column5
FROM distinctrows
;
于 2012-07-15T18:22:42.470 回答
3

如果您不需要DISTINCT,这将很容易。

SELECT Column1,
       Column2,
       Column3,
       Column4,
       Count(Column4) OVER (partition BY Column1, Column2, Column3) AS Column5
FROM   TableA AS t1 

但是 SQL Server 中的窗口聚合当前不支持DISTINCT,因此您可以使用

WITH CTE
     AS (SELECT Column1,
                Column2,
                Column3,
                Count(DISTINCT Column4) AS Column5
         FROM   TableA
         GROUP  BY Column1,
                   Column2,
                   Column3)
SELECT A.Column1,
       A.Column2,
       A.Column3,
       A.Column4,
       C.Column5
FROM   TableA A
       JOIN CTE C
         ON A.Column1 = C.Column1
            AND A.Column2 = C.Column2
            AND A.Column3 = C.Column3 

(为简单起见,我假设这些列不可为空)

于 2012-07-15T18:03:09.663 回答
1

这是你想要的?

SELECT COUNT (DISTINCT t1.Column4) AS Column5,
Column1, Column2, Column3
FROM TableA AS t1
GROUP BY Column1, Column2, Column3;
于 2012-07-15T17:09:35.077 回答
1

这应该这样做:

;WITH 
  countCol4 As
(
    SELECT  Column1, Column2, Column3, Column4
    ,       ROW_NUMBER() OVER(PARTITION BY Column1, Column2, Column3, Column4
                ORDER BY Column4)   As Col4Count
    FROM    TableA  As t1
)
SELECT  Column1, Column2, Column3, Column4
,       COUNT(*) OVER(PARTITION BY Column1, Column2, Column3) As Column5
FROM    countCol4
WHERE   Col4Count = 1
于 2012-07-15T19:08:16.510 回答
0

除了“取消设置”我刚刚阅读但尚未尝试过的“唯一完整分组”模式之外,我只是应用了以下更快的解决方案,这是一个技巧,我这样做是为了避免出现该错误:

 SELECT 
     COUNT (DISTINCT t1.Column4) AS Column5, Column1, Column2, Column3, MAX(Column4) AS Column4
 FROM TableA AS t1 
 GROUP BY Column1, Column2, Column3;

我在 Column4 上有字符值。这似乎没问题,我现在看到 Column5 中的值范围为 1-6,正如我所预料的那样。谢谢!

警告:这不是一个好的答案。原因请参见下面的评论。

于 2012-07-15T17:39:06.553 回答