在SQL中使用where条件对两个聚合查询进行划分?

时间:2014-12-09 04:29:38

标签: sql sql-server

尝试搜索解决方案无法找到它。

我需要按型号比较汽车上的缺陷数量,只比较某种类型的缺陷,并将其与按型号划分的汽车总数进行比较,以获得一定的缺陷,例如

select car,count(distinct model) 
where defect_code=123 
group by car

select car,count(distinct model) group by car

我该如何撰写此查询?优化的方式将是优选的。

2 个答案:

答案 0 :(得分:0)

尝试加入

SELECT car,
       Df_cnt / T_cnt
FROM   (SELECT car,
               Count(DISTINCT model) Df_cnt From tablename
        WHERE  defect_code = 123
        GROUP  BY car) A
       JOIN (SELECT car,
                    Count(DISTINCT model) T_cnt from tablename
             GROUP  BY car) b
         ON A.car = b.car 

答案 1 :(得分:0)

以下是示例代码

SELECT * INTO #TEMP
FROM
(
SELECT 'MARUTI' CAR,'SWIFT' MODEL,123 DEFECT_CODE
UNION ALL
SELECT 'MARUTI' CAR,'ALTO' MODEL,123 DEFECT_CODE
UNION ALL
SELECT 'HYUNDAI' CAR,'ACCENT' MODEL,123 DEFECT_CODE
UNION ALL
SELECT 'NISSAN' CAR,'DATSON' MODEL,123 DEFECT_CODE
UNION ALL
SELECT 'HONDA' CAR,'CITY' MODEL,123 DEFECT_CODE
UNION ALL
SELECT 'HYUNDAI' CAR,'ACCENT' MODEL,115 DEFECT_CODE
UNION ALL
SELECT 'NISSAN' CAR,'DATSON' MODEL,117 DEFECT_CODE
UNION ALL
SELECT 'HONDA' CAR,'CITY' MODEL,118 DEFECT_CODE
)TAB

查询CAR的缺陷车辆数量

SELECT  DISTINCT CAR,DEFECT_CODE,COUNT(MODEL) OVER(PARTITION BY CAR) CARCOUNT 
FROM #TEMP
WHERE DEFECT_CODE=123

结果

enter image description here

查询CAR车型的缺陷车辆数量

SELECT *,COUNT(MODEL) OVER(PARTITION BY CAR,MODEL) CARMODELCOUNT 
FROM #TEMP
WHERE DEFECT_CODE=123

结果

enter image description here