0

我想查询一个表一次,因为查询这个表的时间大约是 8-12 分钟,查询两次实在是太长了。表中有一个标志用于识别内部与外部结果。我想要这个标志是内部的 A 列和 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 列并且只访问数据库一次。

4

1 回答 1

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')
于 2012-04-10T16:26:00.153 回答