表创建查询

时间:2018-12-31 12:37:33

标签: sql-server

我想基于同一列的两个条件对值进行计数。

就像

表名:状态

((TextView) detailsViewHolder.viewTypes[i]).setText("A Text");

输出类似:

----|-------|------------|
Id  | name  |  status    |
----|-------|------------|
1   |   tg1 |    success |
2   |   tg1 |    Reject  |
3   |   tg2 |    success |

2 个答案:

答案 0 :(得分:3)

相关查询可以显示预期结果:

create Table #Table
(
    Id int,
    NameTg varchar(128),
    StatusTg varchar(128)
)

Insert into #Table
(
    Id,
    NameTg,
    StatusTg
)

SELECT 1,'tg1','success'
UNION
SELECT 2,'tg1','success'
UNION
SELECT 3,'tg2','success'
UNION
SELECT 4,'tg2','Reject'

SELECT NameTg, 
    SUM(CASE WHEN StatusTg = 'success' THEN 1 ELSE 0 END) AS Success_count,
    SUM(CASE WHEN StatusTg = 'Reject' THEN 1 ELSE 0 END) AS Reject_count
FROM #Table
GROUP BY NameTg

DROP TABLE  #Table

结果:

NameTg   Success_count  Reject_count
tg1           2               0
tg2           1               1

答案 1 :(得分:2)

您可以将数据透视用作

SELECT * 
FROM 
    (
      SELECT Name, 
             Status 
      FROM T
    ) TT 
PIVOT 
(
  COUNT(Status) 
  FOR Status IN (success,Rejected)
) PVT

Demo