查询表来重组数据

时间:2016-11-25 10:39:42

标签: sql sql-server

我有下表,tblCPDates

 cDate date
 cp nvarchar(10)

数据示例

 cDate       cp
 2016-01-01  AB
 2016-01-01  MN
 2016-02-01  EF
 2016-03-01  AB
 2016-04-01  MN

我想要什么

 cDate       AB   MN    EF
 2016-01-01  1    1     0
 2016-02-01  0    0     1
 2016-03-01  1    0     0
 2016-04-01  0    1     0

这可能吗?

我尝试了以下内容,但显然只返回上一个日期

select * from
(
   select distinct cDate, cp from tblCPDDates
)source pivot(max(cDate) for cp in ([AB], [MN], [EF])) as pvt

4 个答案:

答案 0 :(得分:3)

您可以使用汇总的CASE;

执行此操作

样本数据

CREATE TABLE #tblCPDates (cDate date, cp nvarchar(10))
INSERT INTO #tblCPDates (cDate, cp)
VALUES
 ('2016-01-01','AB')
,('2016-01-01','MN')
,('2016-02-01','EF')
,('2016-03-01','AB')
,('2016-04-01','MN')

查询

SELECT
     cDate
    ,SUM(CASE WHEN cp = 'AB' THEN 1 ELSE 0 END) AB
    ,SUM(CASE WHEN cp = 'MN' THEN 1 ELSE 0 END) MN
    ,SUM(CASE WHEN cp = 'EF' THEN 1 ELSE 0 END) EF
FROM #tblCPDates
GROUP BY cDate

输出

cDate       AB  MN  EF
2016-01-01  1   1   0
2016-02-01  0   0   1
2016-03-01  1   0   0
2016-04-01  0   1   0

答案 1 :(得分:2)

试试这个:通过使用pivot更容易:

     CREATE TABLE #tblCPDates (cDate date, cp nvarchar(10))
      INSERT INTO #tblCPDates (cDate, cp)
       VALUES
      ('2016-01-01','AB')
      ,('2016-01-01','MN')
      ,('2016-02-01','EF')
      ,('2016-03-01','AB')
      ,('2016-04-01','MN')



    select *
     from 
      (
         select cDate, cp
         from #tblCPDates
      ) src
     pivot
     (
       Count(cp)
       for cp in ([AB], [MN],[EF])
     ) piv;

答案 2 :(得分:1)

使用pivot获取结果:

`CREATE TABLE #table(Id INT,cDate DATE,cp VARCHAR(10))
INSERT INTO #table(Id,cDate ,cp )
SELECT 1,'2016-01-01','AB' UNION ALL
SELECT 1,'2016-01-01','MN' UNION ALL
SELECT 1,'2016-02-01','EF' UNION ALL
SELECT 1,'2016-03-01','AB' UNION ALL
SELECT 1,'2016-04-01','MN'

SELECT cDate,ISNULL([AB],0) [AB],ISNULL([MN],0) [MN],ISNULL([EF],0) [EF]
FROM
( SELECT Id,cDate ,cp FROM #table ) A PIVOT (MAX(Id) FOR cp IN ([AB],[MN],[EF])) pvt`

答案 3 :(得分:1)

TryThis。

            select 
            cDate       ,
            case when ab='AB' then 1 else 0 end  as AB,
            case when MN='MN' then 1 else 0 end  as MN,
            case when EF='EF' then 1 else 0 end  as EF
            from
            (
               select distinct cDate, cp from tblCPDates
            )source pivot(max(cp) for cp in ([AB], [MN], [EF])) as pvt