使用和不使用参数计算同一列中的记录

时间:2012-11-15 14:08:24

标签: sql sql-server sql-server-2008

我在查询时遇到了一些麻烦,并希望有人可以提供帮助。我尝试过搜索解决方案,但似乎无法找到与我的搜索字词类似的情况。

以下是我要找的内容:

我有一个包含三列的表,需要返回第一列中的值,以及第二列中两个值的计数。一个计数基于参数,另一个计数是总计数。理想情况下,我只想返回第一列中具有相同计数的值。

例如:

Part Number | Make ID
ABC123      | 1<br>
ABC123      | 1<br>
ABC123      | 3<br>
DEF456      | 1<br>
DEF456      | 1

Part Number | Count of Apps Where Make ID = 1| Count of Total Apps
ABC123      |                              2 | 3
DEF456      |                              2 | 2

我到目前为止的查询将返回具有参数值的部件号的应用总数,但是我需要它来返回两个计数:

SELECT apps.part#, 
       COUNT(DISTINCT application#)apps 
FROM   [mytable] AS apps 
       INNER JOIN (SELECT part# 
                   FROM   [mytable] 
                   WHERE  make = '1') AS sz 
               ON sz.part# = apps.part# 
GROUP  BY apps.part# 
ORDER  BY 1 

非常感谢任何帮助!

谢谢大家!我收到了几个正确的答案,并选择了第一个给出的答案:

SELECT part#, 
       COUNT(DISTINCT CASE WHEN make = '1' THEN application# END) make1_apps,
       COUNT(DISTINCT application#) total_apps
FROM   [mytable]
GROUP  BY part#
HAVING COUNT(DISTINCT CASE WHEN make = '1' THEN application# END)
     = COUNT(DISTINCT application#)
ORDER  BY part#

再次感谢!

4 个答案:

答案 0 :(得分:5)

试试这个:

SELECT
    apps.part#
,   COUNT(*)
,   SUM(CASE WHEN make = '1' THEN 1 ELSE 0 END)
FROM [mytable]
GROUP BY apps.part#

此解决方案通过计算总和来替换计数,并为匹配项提供1,为不匹配项提供0

要过滤掉两个计数不同的记录,请添加HAVING子句:

SELECT
    apps.part#
,   COUNT(*)
,   SUM(CASE WHEN make = '1' THEN 1 ELSE 0 END)
FROM [mytable]
GROUP BY apps.part#
HAVING SUM(CASE WHEN make = '1' THEN 1 ELSE 0 END) = COUNT(*)

答案 1 :(得分:4)

SELECT [Part Number],
       SUM(CASE WHEN [Make ID] = 1 THEN 1 ELSE 0 END),
       COUNT(*)
FROM tableName
GROUP BY [Part Number]

更新1

SELECT [Part Number],
       SUM(CASE WHEN [Make ID] = 1 THEN 1 ELSE 0 END),
       COUNT(*)
FROM tableName
GROUP BY [Part Number]
HAVING SUM(CASE WHEN [Make ID] = 1 THEN 1 ELSE 0 END) = COUNT(*)

答案 2 :(得分:2)

另一种更类似于你的方式:

select d.[Part Number], count(d.[Part Number]), o.ones
from
  data d
cross apply
(
  select count(*)
  from data d2
  where d2.[Part Number] = d.[Part Number]
      and d2.[Make ID] = 1
) o (ones)
group by d.[Part Number],  o.ones

SQLFiddle

完成第二次请求添加:

having count(d.[Part Number]) = o.ones

答案 3 :(得分:1)

SELECT part#, 
       COUNT(DISTINCT CASE WHEN make = '1' THEN application# END) make1_apps,
       COUNT(DISTINCT application#) total_apps
FROM   [mytable]
GROUP  BY part#
HAVING COUNT(DISTINCT CASE WHEN make = '1' THEN application# END)
     = COUNT(DISTINCT application#)
ORDER  BY part#; 

HAVING子句确保两个计数匹配。