在一个查询中收集两个查询

时间:2015-03-19 12:08:39

标签: sql sql-server

我可以在一个查询中收集这两个查询吗?

INSERT INTO [dbo].[acceuil](libelle,value,categorie,param)
SELECT 'Scom',count(*),'event','month1'
FROM [dbo].[full]
WHERE date_reception BETWEEN @StartDate AND @EndDate and event_class LIKE '%MOM%'

   INSERT INTO [dbo].[acceuil](libelle,value,categorie,param)
SELECT 'Spectrum',count(*),'event','month1'
FROM [dbo].[full]
WHERE date_reception BETWEEN @StartDate AND @EndDate and event_class LIKE '%SPECTRUM%'

这些查询之间的区别在于(LIKE'%Spectrum%')(SELECT Spectrum)

2 个答案:

答案 0 :(得分:4)

or子句中的

where基本上可以做你想要的:

INSERT INTO [dbo].[acceuil](libelle,value,categorie,param)
    SELECT (CASE WHEN event_class LIKE '%MOM%' THEN 'Scom'
                 WHEN event_class LIKE '%SPECTRUM%' THEN 'Spectrum'
            END), count(*), 'event', 'month1'
    FROM [dbo].[full]
    WHERE date_reception BETWEEN @StartDate AND @EndDate 
          (event_class LIKE '%MOM%' OR event_class LIKE '%SPECTRUM%')
    GROUP BY (CASE WHEN event_class LIKE '%MOM%' THEN 'Scom'
                   WHEN event_class LIKE '%SPECTRUM%' THEN 'Spectrum'
              END);

我意识到您还需要group by来汇总libelle

编辑:

编写查询的一种更简单的方法是:

INSERT INTO [dbo].[acceuil](libelle,value,categorie,param)
    SELECT libelle, count(*), 'event', 'month1'
    FROM (SELECT f.*,
                 (CASE WHEN event_class LIKE '%MOM%' THEN 'Scom'
                       WHEN event_class LIKE '%SPECTRUM%' THEN 'Spectrum'
                  END) as libelle
          FROM [dbo].[full] f
         ) f
    WHERE libelle IS NOT NULL
    GROUP BY libelle;

这样可以更轻松地添加您可能正在寻找的其他值。

答案 1 :(得分:0)

您可以使用UNION ALL

    INSERT  INTO [dbo].[acceuil]
    ( libelle ,
      value ,
      categorie ,
      param
    )
    SELECT  'Scom' ,
            COUNT(*) ,
            'event' ,
            'month1'
    FROM    [dbo].[full]
    WHERE   date_reception BETWEEN @StartDate AND @EndDate
            AND event_class LIKE '%MOM%'

    UNION ALL

    SELECT  'Spectrum' ,
            COUNT(*) ,
            'event' ,
            'month1'
    FROM    [dbo].[full]
    WHERE   date_reception BETWEEN @StartDate AND @EndDate
            AND event_class LIKE '%SPECTRUM%'

INSERT  INTO [dbo].[acceuil]
        ( libelle ,
          value ,
          categorie ,
          param
        )
        SELECT  CASE WHEN event_class LIKE '%MOM%' THEN 'Scom'
                     WHEN event_class LIKE '%SPECTRUM%' THEN 'Spectrum'
                END ,
                COUNT(*) ,
                'event' ,
                'month1'
        FROM    [dbo].[full]
        WHERE   date_reception BETWEEN @StartDate AND @EndDate
                AND (event_class LIKE '%MOM%' OR event_class LIKE '%SPECTRUM%')