具有Sum和多个Where条件的SQL请求

时间:2016-11-21 10:34:30

标签: sql sql-server

我的表格包含有关访问次数,访问日期,访客类型和数量的数据。它看起来像:

| Date_Visit | Type  | Nb_Visitors |
 04-05-2015   Intern    3
 08-09-2015   Extern    10
 13-09-2015   Intern    2
 17-09-2015   Intern    6
    ...        ...      ...

我希望输出如下:

|DateMonth | Nb_Visit_Extern | Nb_Visitors_Extern | Nb_Visit_Intern | Nb_Visitors_Intern |
 05-2015     1                 3                   0                  0
 09-2015     1                 10                  2                  8

我的查询如下:

SELECT CONVERT (VARCHAR(7), [Date_Visit], 20) As DateMonth,
COUNT(*) Nb_Visit_Extern,
SUM(Nb_Visitors) Nb_Visitors_Extern
From MyTable
Where [Type] = 'Extern'
GROUP BY CONVERT (VARCHAR(7), [Date_Visit], 20)
ORDER BY CONVERT (VARCHAR(7), [Date_Visit], 20) ASC

SELECT CONVERT (VARCHAR(7), [Date_Visit], 20) As DateMonth,
COUNT(*) as Nb_Visit_Intern,
SUM(Nb_Visitors) as Nb_Visitors_Intern
From MyTable
Where [Type] = 'Intern'
GROUP BY CONVERT (VARCHAR(7), [Date_Visit], 20)
ORDER BY CONVERT (VARCHAR(7), [Date_Visit], 20) ASC

我尝试使用CASE条件,但它不适用于SUM语句。 我该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以使用SQL的简单Count和Sum函数。

    SELECT CONVERT (VARCHAR(7), [Date_Visit], 20) As DateMonth,
COUNT(case when Type = 'Extern' then 1 else 0 end) Nb_Visit_Extern,
SUM(case when Type = 'Extern' then [Nb_Visitors] else 0 end) Nb_Visitors_Extern,
COUNT(case when Type = 'Intern' then 1 else 0 end) Nb_Visit_Intern,
SUM(case when Type = 'Intern' then [Nb_Visitors] else 0 end) Nb_Visitors_Intern
GROUP BY CONVERT (VARCHAR(7), [Date_Visit], 20)
ORDER BY CONVERT (VARCHAR(7), [Date_Visit], 20) ASC

答案 1 :(得分:0)

您应该使用case表达式,例如

SUM(case when Type = 'Extern' then 1 else 0 end) as Nb_Visitors_Extern