如何从一列中计算sql,并将其显示在两列中

时间:2014-03-24 05:53:50

标签: sql

我有一张这样的表:

    idrecord          |    date
----------------------------------------------
INC-20140308102029    | 2014-03-08 00:00:00.000
INC-20140308102840    | 2014-03-06 00:00:00.000
INC-20140310164404    | 2014-03-10 00:00:00.000
INC-20140311075714    | 2014-03-09 00:00:00.000
NRM-20140310130512    | 2014-04-02 00:00:00.000
NRM-20140311134720    | 2014-03-11 00:00:00.000
USF-20140317212232    | 2014-03-17 00:00:00.000
USF-20140321075402    | 2014-03-18 00:00:00.000
USF-20140321083137    | 2014-03-21 00:00:00.000

如何计算此表并显示如下结果:

month      | INC | NRM | USF
march      |  4  |  1  |  3
April      |  0  |  1  |  0

谢谢

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT convert(char(3), date, 0) AS Month,
    SUM(Case when LEFT(idrecord,3) = 'INC' then 1 else 0 end) as 'INC',
    SUM(Case when LEFT(idrecord,3) = 'NRM' then 1 else 0 end) as 'NRM',
    SUM(Case when LEFT(idrecord,3) = 'USF' then 1 else 0 end) as 'USF'
FROM Table1
Group By convert(char(3), date, 0)

Fiddle Demo

或:

SELECT datename(mm, date) AS Month,
    SUM(Case when LEFT(idrecord,3) = 'INC' then 1 else 0 end) as 'INC',
    SUM(Case when LEFT(idrecord,3) = 'NRM' then 1 else 0 end) as 'NRM',
    SUM(Case when LEFT(idrecord,3) = 'USF' then 1 else 0 end) as 'USF'
FROM Table1
Group By datename(mm, date)

Fiddle Demo

输出:

    month      | INC | NRM | USF
    march      |  4  |  1  |  3
    April      |  0  |  1  |  0

答案 1 :(得分:1)

根据字符串匹配与否,您使用大小写计数1或零。使用总和进行计数。

select
  extract(month from thedate) as whichmonth,
  sum( case when idrecord like 'INC%' then 1 else 0 end) as inc,
  sum( case when idrecord like 'NRM%' then 1 else 0 end) as nrm,
  sum( case when idrecord like 'USF%' then 1 else 0 end) as usf
from mytable
group by extract(month from thedate);

从日期中提取月份的功能可能因dbms而异。如果提取不适合您,请在Google中查看相应的功能。

不要使用列的名称日期。日期是SQL中的保留字。

答案 2 :(得分:1)

尝试这个

select month (date) as month,
      count( case when idrecord like 'INC%' then 1 else 0 end) as inc,
      count( case when idrecord like 'NRM%' then 1 else 0 end) as nrm,
      count( case when idrecord like 'USF%' then 1 else 0 end) as usf
    from table
    group by month;