不同的值作为新列&计数

时间:2016-04-19 02:13:53

标签: sqlite pivot

我正在尝试使用SQLite从表中生成摘要,如下所示。

我需要聚合1)每个模型被驱动的次数,2)总距离驱动& 3)获得驱动程序col& amp;计算每个驱动程序驱动特定模型的次数 - GROUP BY modelCOUNT(model)& SUM(distance)将有助于1& 2 - “我需要最后一部分#3的帮助,找到每列不同值的出现次数的正确方法是什么,并将它们添加为每个模型的新列?

我的表是:

id  model  datetime     driver   distance
---|-----|------------|--------|---------
1  | S   | 04/03/2009 | john   | 399 
2  | X   | 04/03/2009 | juliet | 244
3  | 3   | 04/03/2009 | borat  | 555
4  | 3   | 03/03/2009 | john   | 300
5  | X   | 03/03/2009 | juliet | 200
6  | X   | 03/03/2009 | borat  | 500
7  | S   | 24/12/2008 | borat  | 600
8  | X   | 01/01/2009 | borat  | 700

结果将是

id  model| drives   distance  john   juliet  borat
---|-----|--------|---------|------|------ |------
1  | S   | 2      | 999     | 1    |   0   |  1
2  | X   | 4      | 1644    | 0    |   2   |  2
3  | 3   | 2      | 855     | 1    |   0   |  1

2 个答案:

答案 0 :(得分:1)

好的......这次我明白了!

select new_table.model, count (new_table.model) as drives, sum (new_table.distance) as distance, 
       sum(case when driver = 'john' then 1 else 0 end) as john,
       sum(case when driver = 'juliet' then 1 else 0 end) as juliet,
       sum(case when driver = 'borat' then 1 else 0 end) as borat
from new_table
group by model

答案 1 :(得分:-1)

它不是100%,但这应该可以让你在那里大部分时间。

CREATE TABLE DBO.TEST_TABLE (ID INT,MODEL CHAR(1),DATETIME VARCHAR(255),DRIVER VARCHAR(255),DISTANCE INT)

INSERT INTO DBO.TEST_TABLE
VALUES
 (1,'S','04/03/2009','JOHN',399)
,(2,'X','04/03/2009','JULIET',244)
,(3,'3','04/03/2009','BORAT',555)
,(4,'3','03/03/2009','JOHN',300)
,(5,'X','03/03/2009','JULIET',200)
,(6,'X','03/03/2009','BORAT',500)
,(7,'S','24/12/2008','BORAT',600)
,(8,'X','01/01/2009','BORAT',700)


Declare @Query_ nvarchar(MAX)
Declare @Cols_For_Pivot_ nvarchar(MAX) 


SELECT @Cols_For_Pivot_= COALESCE(@Cols_For_Pivot_ + ',','') + QUOTENAME(DRIVER)
FROM (SELECT DISTINCT DRIVER FROM DBO.TEST_TABLE) AS PivotTable

IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL DROP TABLE #TEMP
SET   @Query_ = 
    N'SELECT DISTINCT
             MODEL
            ,COUNT(DATETIME) OVER(PARTITION BY MODEL)   AS DRIVES
            ,SUM(DISTANCE) OVER(PARTITION BY MODEL)  AS DISTANCE
            , ' +   @Cols_For_Pivot_ + '
    INTO #TEMP
    FROM DBO.TEST_TABLE
    PIVOT(COUNT(DRIVER) 
          FOR DRIVER IN (' + @Cols_For_Pivot_ + ')) AS P'

EXEC sp_executesql @Query_   

enter image description here