使用带有一个没有连接的结果流的过滤器查询1表两次?

时间:2012-04-10 16:15:49

标签: sql sql-server

我想查询一次表,因为查询此表的时间大约是8-12分钟,查询它的时间太长了。表格中有一个标志,用于识别内部和外部结果。我想要A和A列的总和。 B标志的内部和B和B的总和。 C& D这个标志是外部的..现在它的两个单独的查询连接在一起......

这是第一个查询的示例

Select
CONVERT(varchar(10), right([week_name],10), 111) as DatePeriod --weekly
,[Group] as [Group]
,SUM([columnA]) as [columnA_int]
,SUM([columnB]) as [columnB_int]    
from  myTbl
where internal_external = 'internal' 
group by 
CONVERT(varchar(10), right([week_name],10), 111),[Group]

第二次查询

Select
CONVERT(varchar(10), right([week_name],10), 111) as DatePeriod --weekly
,[Group] as [Group]
,SUM([columnB]) as [columnB_ext]
,SUM([columnC]) as [columnC_ext]
,SUM([columnC]) as [columnC_ext]        
from  myTbl
where internal_external = 'external' 
group by 
CONVERT(varchar(10), right([week_name],10), 111),[Group]

理想情况下,一个查询所有5列,只打了一次DB。

1 个答案:

答案 0 :(得分:3)

试试这样:

SELECT
    internal_external
    ,CONVERT(varchar(10), right([week_name],10), 111) as DatePeriod --weekly
    ,[Group] as [Group]
    ,SUM(CASE 
            WHEN internal_external='internal' THEN [columnA]
            ELSE 0 
          END) as [columnA_int]
    ,SUM([columnB]) as [columnB_intext] 
    ,SUM(CASE 
            WHEN internal_external='external' THEN [columnC]
            ELSE 0 
          END) as [columnC_ext]
    ,SUM(CASE 
            WHEN internal_external='external' THEN [columnC]
            ELSE 0 
          END) as [columnC_ext2]
FROM  myTbl
GROUP BY
    internal_external
    ,CONVERT(varchar(10), right([week_name],10), 111)
    ,[Group]
-- use the next lines if there are other values for internal_external
HAVING 
    internal_external IN('internal', 'external')

或者,如果你想放弃internal_external列:

SELECT
    CONVERT(varchar(10), right([week_name],10), 111) as DatePeriod --weekly
    ,[Group] as [Group]
    ,SUM(CASE 
            WHEN internal_external='internal' THEN [columnA]
            ELSE 0 
          END) as [columnA_int]
    ,SUM(CASE 
            WHEN internal_external='internal' THEN [columnB]
            ELSE 0 
          END) as [columnB_int]
    ,SUM(CASE 
            WHEN internal_external='external' THEN [columnB]
            ELSE 0 
          END) as [columnB_ext]
    ,SUM(CASE 
            WHEN internal_external='external' THEN [columnC]
            ELSE 0 
          END) as [columnC_ext]
FROM  myTbl
GROUP BY
    internal_external
    ,CONVERT(varchar(10), right([week_name],10), 111)
    ,[Group]
-- use the next lines if there are other values for internal_external
HAVING 
    internal_external IN('internal', 'external')