把它写在一个sql语句中

时间:2013-11-22 07:56:50

标签: sql sql-server tsql

我有一个包含2列的表:名称和指示(成功或失败), 我需要创建单个SQL语句来获得带有3列的结果:名称,#项目的总出现次数和Failere的数量

如何在一个单独的sql语句中编写它

4 个答案:

答案 0 :(得分:1)

select t.name, count(t.name),count(case When t.indication= 1 Then t.indication end) from     table1 t
group by t.name

这是Fiddle

答案 1 :(得分:1)

我做了一个SQL Fiddle来演示:

SELECT
  name,
  COUNT(success) AS `count`,
  SUM(CASE success WHEN 'F' THEN 1 ELSE 0 END) AS `failures` 
FROM tbl
GROUP BY name

答案 2 :(得分:0)

试试这个,看看它能不能得到你想要的结果:

SELECT X.name, COUNT(X.name), 
    (SELECT COUNT(Y.indication) FROM table_name Y WHERE Y.indication = 1 AND Y.name = X.name)
FROM table_name X
GROUP BY X.name

答案 3 :(得分:0)

SELECT 
      table_name.name
     ,COUNT(table_name.name) AS cnt 
     ,SUM(CASE WHEN table_name.indication = 1 THEN 1 ELSE 0 END) AS FailCount
FROM YOUR_TABLE AS table_name 
GROUP BY table_name.name

实际上,这取决于你如何保存指示 如果你使用位字段,使用true(1)= failed和false(0)= success,那么你可以这样做:

   SELECT 
          table_name.name
         ,COUNT(table_name.name) AS cnt 
         ,SUM(CAST(table_name.indication AS integer)) AS FailCount
    FROM YOUR_TABLE AS table_name 
    GROUP BY table_name.name