3

我正在寻找有关如何优化此查询的想法。我已经评估了执行计划,但它没有为缺少索引提供任何想法,所以只是好奇编写查询是否更好(不同的策略)会导致更快/更轻的查询。

SELECT [Place], COUNT([Place]) 
FROM (
    SELECT scoresid, REPLACE(REPLACE(EventPlace1,'T', ''),'*','') [Place] 
        FROM [MS.Prod]..mso_scores UNION
    SELECT scoresid, REPLACE(REPLACE(EventPlace2,'T', ''),'*','') 
        FROM [MSO.Prod]..mso_scores UNION
    SELECT scoresid, REPLACE(REPLACE(EventPlace3,'T', ''),'*','') 
        FROM [MSO.Prod]..mso_scores UNION
    SELECT scoresid, REPLACE(REPLACE(EventPlace4,'T', ''),'*','') 
        FROM [MSO.Prod]..mso_scores UNION
    SELECT scoresid, REPLACE(REPLACE(EventPlace5,'T', ''),'*','') 
        FROM [MSO.Prod]..mso_scores UNION
    SELECT scoresid, REPLACE(REPLACE(EventPlace6,'T', ''),'*','') 
        FROM [MSO.Prod]..mso_scores UNION
    SELECT scoresid, REPLACE(REPLACE(AAPlace,'T', ''),'*','') 
        FROM [MSO.Prod]..mso_scores
) data1 
JOIN [MSO.Prod]..mso_scores scores ON scores.scoresid = data1.scoresid
    AND scores.usagnum = '274246' 
    AND scores.TeamResult='N'
WHERE data1.Place IN ('1', '2', '3')
GROUP BY Place

快速解释一下:有 6 个活动地点字段。这些字段中的数据看起来像“1”、“2”、“1T”、“3”、“5T”;其中“T”是平局。我只关心数字 1、2、3,所以我从该位置解析出“T”或“*”,然后将查询分组以进行计数。

他们有多少个第一名,多少个第二名,等等。

4

1 回答 1

3

试试这个(2008 年及更高版本)-

SELECT [Place], COUNT(1)
FROM (
    SELECT [Place] = REPLACE(REPLACE(t.[Place], 'T', ''), '*', '')  
    FROM dbo.mso_scores r
    OUTER APPLY (
        VALUES 
            (EventPlace1),
            (EventPlace2),
            (EventPlace3),
            (EventPlace4),
            (EventPlace5),
            (EventPlace6),
            (AAPlace)
    ) t([Place])
    WHERE r.usagnum = '274246' 
        AND r.TeamResult = 'N'
) d
WHERE d.Place IN ('1', '2', '3')
GROUP BY d.Place

有关其他信息,请阅读本主题:通过分析查询计划优化 SQL 查询的技巧

于 2013-09-04T05:56:06.097 回答