distinct values as new columns & count

走远了吗. 提交于 2020-01-07 02:26:26

问题


I'm trying to generate a summary from a table using SQLite as below.

I need to aggregate 1) number of times each model was driven, 2) total distance driven & 3) get distinct values for driver col & count the number of times each driver has driven the particular model - GROUP BY modelwith COUNT(model) & SUM(distance) will help with 1 & 2 - `I need help with the last part #3 , what is the right approach to find number of occurrences for each distinct values of a column and add them as new columns for each model ?

My table is:

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

Result would be

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

回答1:


OK... this time I got it!

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



回答2:


It's not 100%, but this should get you most of the way there.

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_   



来源:https://stackoverflow.com/questions/36707359/distinct-values-as-new-columns-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!