MS SQL计数AS到新列

时间:2017-07-31 14:21:40

标签: sql sql-server database

美好的一天

我的桌子有问题并且计算

TABLE1
COLUMN1       COLUMN2
3              jjd
5              jd
3              jjd
4              kg 
5              jd
48             gjh
446            djj
…               … 

我需要

TABLE1 
COLUMN1 COLUMN2 COLUMN3
3         jj         2
5         jd         2
4         kg         1
48        gjh        1
446       djj        1
...        ...       …

我正在做但但效果不好。

SELECT * , COUNT(Column1) as column3 FROM TABLE1

感谢您帮助我计算

3 个答案:

答案 0 :(得分:0)

尝试使用分组

    SELECT COLUMN1 , 
       COLUMN2 ,
       COUNT(Column1) As COLUMN3 FROM cte_TABLE1
    Group by COLUMN1 ,COLUMN2 
    Order by COLUMN1

使用Window功能

SELECT DISTINCT COLUMN1 , 
       COLUMN2 ,
       COUNT(Column1)OVER(Partition by COLUMN1,COLUMN2 ORder by COLUMN1 ) As COLUMN3 FROM cte_TABLE1

结果

COLUMN1 COLUMN2 column3
-----------------------
3       jjd      2
4       kg       1
5       jd       2
48      gjh      1
446     djj      1

答案 1 :(得分:0)

<post-component *ngFor="let post of posts" [post]="post"></post-component>GROUP BYORDER BY一起使用,将其置于DESC总订单中。

COUNT

输出

SELECT COLUMN1, COLUMN2, COUNT(Column1) AS COLUMN3 
FROM Table1
GROUP BY COLUMN1, COLUMN2
ORDER BY COUNT(Column1) DESC

SQL小提琴:http://sqlfiddle.com/#!6/89f49/4/0

答案 2 :(得分:0)

使用OVER我们可以轻松实现

SELECT  COLUMN1 , 
       COLUMN2 ,
       COUNT(Column1)OVER(Partition by COLUMN1,COLUMN2 ORder by COLUMN1 ) As COLUMN3 FROM cte_TABLE1
Group By COLUMN1,COLUMN2