分组依据,多个计数,多个表SQL Server

时间:2017-05-06 00:56:56

标签: sql sql-server

我有两张表如下:

第一张表:2016

Os          |   Count
------------+----------
Windows 7         8
Windows 7         9
Windows 7        20
Windows 8        30
Linux            15

第二张表:2017

Os          |   Count
------------+----------
Windows 7        35
Windows 7        11
Windows 8        10
Windows 8         8
Linux            10
Ubuntu            3

我自己尝试,但我的挑战是使用GROUP BY功能,同时我计算两个不同表中的两个字段,我总是错误。

提前谢谢你,

更新

对不起,我在解释我的请求时犯了一个错误:我需要写一个查询来得到这样的结果:

    --OS--         --2016--    --2017--
    ------------------------------------
    Windows 7        37             46
    Windows 8        30             18
    Linux            15             10
    Ubuntu           0              3

2 个答案:

答案 0 :(得分:1)

你可以通过以下方式做一个简单的小组:

select a.OS, sum(count) from (
    select * from your2016table
        union all 
    select * from your2017table
    ) a
    group by a.OS

为此你可以使用year作为group by和pivot

;with cte as (
select a.OS, a.[year], SumCt = sum(count) from (
    select *, 2016 as [year] from your2016table
        union all 
    select *, 2017 as [year] from your2017table
    ) a
    group by a.OS, a.[year]
)
select * from cte 
pivot (max(sumct) for [year] in ([2016], [2017])) p

答案 1 :(得分:0)

如果没有$ python -c "import vtk; print vtk.vtkSphereSource()" vtkSphereSource (0xcfdcc0) Debug: Off Modified Time: 39 Reference Count: 2 Registered Events: (none) Executive: 0xae5e00 ErrorCode: Success Information: 0xf6e210 AbortExecute: Off Progress: 0 Progress Text: (None) Theta Resolution: 8 Phi Resolution: 8 Theta Start: 0 Phi Start: 0 Theta End: 360 Phi End: 180 Radius: 0.5 Center: (0, 0, 0) LatLong Tessellation: 0 Output Points Precision: 0 ,您可以执行此操作:

UNION ALL

这也消除了SELECT COALESCE( [2016].[OS], [2017].[OS] ) AS [OS], ( [2016].[Count] + [2017].[Count] ) AS [Count] FROM [2016] FULL OUTER JOIN [2017] ON [2016].[OS] = [2017].[OS] 的需要,假设GROUP BY列不包含重复项。

需要通过OS(而不是GROUP BY)删除重复项,但适用相同的结构:

SELECT DISTINCT

...但是它变得非常笨拙,SELECT COALESCE( [2016-D].[OS], [2017].[OS] ) AS [OS], ( [2016-D].[Count] + [2017].[Count] ) AS [Count] FROM ( SELECT [OS], SUM( [Count] ) FROM [2016] GROUP BY [OS] ) AS [2016-D] FULL OUTER JOIN ( SELECT [OS], SUM( [Count] ) FROM [2017] GROUP BY [OS] ) AS [2017-D] ON [2016].[OS] = [2017].[OS] 方法变得更简单了!

更新

OP修改了他们的问题,说他们想要单独的列 - 所以这就是使用UNION ALL成为理想解决方案的地方:

OUTER JOIN