具有相等条件和计数条件的SQL情况

时间:2018-11-29 12:14:00

标签: sql sql-server

如何执行同时过滤元素的值和计数的查询。

 Select 
 (case 
  when element = 'data1' and (select count(element) from mytable where element='data1') > 15 then '1'
  when element = 'data2' and (select count(element) from mytable where element='data2') > 15 then '2'
            .
            .
            .

  )
    from mytable
    where conditions

有没有快速,简单的方法来实现这一目标?

3 个答案:

答案 0 :(得分:2)

我认为您需要窗口功能:

select (case when element = 'data1' and
                  count(*) over (partition by element) > 15
             then '1'
             when element = 'data2' and
                  count(*) over (partition by element) > 15
             then '2'
        .
        .
        .

     )
from mytable
where conditions

答案 1 :(得分:1)

出于代码清晰和性能的考虑,我将在CTE中分离聚合,然后在联接中调用它。如果表很大,出于性能原因,您可以将结果放在临时表中而不是CTE中。

;WITH ElementCTE 
AS
(
    SELECT element, count(Element) AS count_Element 
    FROM mytable 
    GROUP BY element
    WHERE Conditions
)
SELECT 
CASE ELEMENT
    WHEN 'Data1' AND count_Element > 15 THEN '1'
    WHEN 'Data2' AND count_Element > 15 THEN '2'
FROM mytable AS mt
INNER JOIN Element AS el
ON mt.Element = el.Element
WHERE mt.conditions

答案 2 :(得分:0)

假设您有一张桌子:

CREATE TABLE NULLTEST
(
TransactioNo INT, 
Code VARCHAR(25)
)

INSERT INTO NULLTEST VALUES (NULL, 'TEST1');
INSERT INTO NULLTEST VALUES (NULL, 'TEST2');
INSERT INTO NULLTEST VALUES (1, 'TEST2');

查询看起来像这样:

SELECT 
CASE
    WHEN Code = 'TEST2' AND 
        (SELECT COUNT(1) FROM dbo.NULLTEST n WHERE n.Code = 'TEST2')> 1 THEN '1'            
    WHEN Code = 'TEST1' AND 
        (SELECT COUNT(1)  FROM dbo.NULLTEST n WHERE n.Code ='TEST1')> 1 THEN '2'
    ELSE '3' end Yourcolumn
FROM dbo.NULLTEST t
WHERE ...