对于某人来说,我希望这是一个简单的问题。
我有很多条目,其中一些条目具有重复的Team_ID值。
从本质上讲,想象某人将新数据打包到表中而不想查看它是否已经存在(这是一个假设的例子)。
这是数据(注意Team_ID 1和2重复):
Team_ID Items_sold Total_Sales Team_Size Profit
1 40 280 NULL NULL
2 32 192 NULL NULL
3 56 336 4 NULL
4 23 161 6 NULL
1 NULL NULL 5 NULL
2 NULL NULL 6 100
来自剧本:
SELECT TOP 10000 [Team_ID]
,[Items_sold]
,[Total_Sales]
,[Team_Size]
,[Profit]
FROM [JEC].[dbo].[Small_Try$]
我希望数据在最后看起来像这样:
Team_ID Items_sold Total_Sales Team_Size Profit
1 40 280 5 NULL
2 32 192 6 100
3 56 336 4 NULL
4 23 161 6 NULL
感谢您的帮助
答案 0 :(得分:0)
你试过吗
SELECT TOP 10000
[Team_ID]
,MAX(ISNULL([Items_sold],0))
,MAX(ISNULL([Total_Sales],0))
,MAX(ISNULL([Team_Size],0))
,MAX(ISNULL([Profit],0))
FROM [JEC].[dbo].[Small_Try$]
GROUP BY [Team_ID]
这是假设你想要碰撞时的最大值。您可以使用任何组函数,如sum,min(具有适当的ISNULL值)等
编辑:
SELECT TOP 10000
tg.[Team_ID]
,(SELECT t1.[Items_sold] FROM [JEC].[dbo].[Small_Try$] t1 WHERE t1.[Team_ID] = tg.[Team_ID] AND t1.[Items_sold] IS NOT NULL) as Items_sold
, (SELECT t2.[Total_Sales] FROM [JEC].[dbo].[Small_Try$] t2 WHERE t2.[Team_ID] = tg.[Team_ID] AND t2.[Total_Sales] IS NOT NULL) as Total_Sales
, (SELECT t3.[Items_sold] FROM [JEC].[dbo].[Small_Try$] t3 WHERE t3.[Team_ID] = tg.[Team_ID] AND t3.[Items_sold] IS NOT NULL) as Team_Size
, (SELECT t4.[Profit] FROM [JEC].[dbo].[Small_Try$] t4 WHERE t4.[Team_ID] = tg.[Team_ID] AND t4.[Profit] IS NOT NULL) as Profit
FROM [JEC].[dbo].[Small_Try$] tg
GROUP BY [Team_ID]
我认为现在应该可行了
答案 1 :(得分:0)
使用动态SQL聚合:
declare @sql varchar(max) = 'SELECT TOP 10000
[Team_ID]
'
select @sql = @sql + ',MAX(' + QUOTENAME(name) + ') AS ' + QUOTENAME(name)
from [JEC].[sys].[columns]
where object_id = object_id('Small_Try$')
and name <> 'Team_ID'
set @sql = @sql + 'FROM [JEC].[dbo].[Small_Try$]
GROUP BY [Team_ID]'
EXEC(@sql)
答案 2 :(得分:0)
由于您使用的是SQL Server 2014(2012年已经足够),您可以充分利用FIRST_VALUE()
。我们的想法是,对于每一列,您选择第一个值,并在OVER()
order子句中按降序使用列本身。这样,任何非NULL值都将出现在NULL之前并将被选中。每当所有值都为NULL时,您将获得NULL。如果您使用DISTINCT
修饰符,则每个团队只能获得一行:
SELECT DISTINCT Team_ID,
FIRST_VALUE(Items_sold) OVER(PARTITION BY Team_ID ORDER BY Items_sold DESC),
FIRST_VALUE(Total_Sales) OVER(PARTITION BY Team_ID ORDER BY Total_Sales DESC),
FIRST_VALUE(Team_Size) OVER(PARTITION BY Team_ID ORDER BY Team_Size DESC),
FIRST_VALUE(Profit) OVER(PARTITION BY Team_ID ORDER BY Profit DESC)
FROM [Small_Try$]
您可以在SQLFiddle上查看它的实时工作原理。我已经将最后一行分成2个部分,因此您可以看到它存在多于2时的功能,并注意到Profit列为varchar()
,并且仍然有效。