性能调整tSQL查询次数(*)&子查询

时间:2016-06-14 01:24:15

标签: tsql count subquery

我知道有更好的方法可以做我想在这里完成的事情。虽然查询有效,但我担心它的性能会随着应用于数据集的增长而受到影响。

我甚至不需要有人重写我所拥有的东西,如果他们愿意指出我应该研究的主题方向我会非常感激。

我尝试使用此查询返回的是对某个状态或更高级别的记录数量的计数。

提前感谢您的帮助!

SELECT ( SELECT count(*) FROM TABLE1 c1 WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND (c1.U_KEY1 = '' or c1.U_KEY1 IS NULL) ) ) AS 'STATUS is EMPTY' , ( SELECT count(*) FROM TABLE1 c1 WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '70' ) ) AS 'STATUS > 70' , ( SELECT count(*) FROM TABLE1 c1 WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '50' ) ) AS 'STATUS > 50' , ( SELECT count(*) FROM TABLE1 c1 WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '30' ) ) AS 'STATUS > 30' , ( SELECT count(*) FROM TABLE1 c1 WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '10' ) ) AS 'STATUS > 10'

2 个答案:

答案 0 :(得分:2)

您可以使用CASE语句将所有子查询转换为单个查询:

SELECT
    SUM(CASE WHEN c1.U_KEY1 = '' OR c1.U_KEY1 IS NULL THEN 1 ELSE 0 END) AS 'STATUS IS EMPTY',
    SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '70'           THEN 1 ELSE 0 END) AS 'STATUS > 70',
    SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '50'           THEN 1 ELSE 0 END) AS 'STATUS > 50',
    SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '30'           THEN 1 ELSE 0 END) AS 'STATUS > 30',
    SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '10'           THEN 1 ELSE 0 END) AS 'STATUS > 10'
FROM TABLE1 c1
WHERE c1.U_KEY3 NOT LIKE 'z%'

但这可能不会像单个子查询一样快。

答案 1 :(得分:1)

我会像这样转过问题:

DECLARE @t TABLE (Id INT, U_Key1 VARCHAR(4) null);

INSERT INTO @t (id,U_Key1)
VALUES
(1,null),
(2,'902'),
(3,'452'),
(4,'401'),
(5,'103'),
(6,'359'),
(7,'335'),
(8,'772'),
(9,'143'),
(10,'222'),
(11,'664'),
(12,'992'),
(13,'122'),
(14,'332'),
(15,'421'),
(16,'622'),
(17,'982'),
(18,'1234'),
(19,null),
(20,'012');

WITH A AS (
    SELECT CAST(LEFT(U_Key1,2) AS INT) val FROM @t
), limits AS (
    SELECT  10 limitval, 'Status >= 10' limittext
    UNION ALL
    SELECT  30 , 'Status >= 30'
    UNION ALL
    SELECT  50 , 'Status >= 50'
    UNION ALL
    SELECT  70 , 'Status >= 70'

), Counts AS (
    SELECT 'Status is empty' Limittext, COUNT(id) Count FROM @t 
    WHERE U_Key1 IS null
    UNION ALL
    SELECT l.limittext, COUNT( A.val) Count FROM A
    CROSS JOIN limits l
    WHERE A.val >= l.limitval
    GROUP BY l.limittext
    )
    SELECT * FROM Counts

产生结果:

Status is empty 2
Status >= 10    17
Status >= 30    12
Status >= 50    6
Status >= 70    4