0

我在查询时遇到了一些问题,希望有人能提供帮助。我曾尝试寻找解决方案,但似乎无法用我的搜索词找到类似的场景。

这是我正在寻找的:

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

例如:

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

4 回答 4

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(*)
于 2012-11-15T14:11:38.797 回答
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(*)
于 2012-11-15T14:11:57.020 回答
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
于 2012-11-15T14:15:53.563 回答
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 子句确保两个计数匹配。

于 2012-11-15T14:17:29.347 回答