Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQL Server:如何合并行_Python_Sql Server_Pandas_Pymssql - Fatal编程技术网

Python SQL Server:如何合并行

Python SQL Server:如何合并行,python,sql-server,pandas,pymssql,Python,Sql Server,Pandas,Pymssql,我有一个类似的问题 select top 10 Col1,Col2,Col3 from tab1 这让我 (1, 1, 1) (5, 2, 59) (8, 3, 69) (9, 4, 70) (10, 5, 71) (11, 6, 72) (11, 7, 73) (11, 8, 74) (11, 9, 75) (11, 10, 76) 我想把结果浓缩为 (1, 1, 1) (5, 2, 59) (8, 3, 69) (9, 4, 70) (10, 5,

我有一个类似的问题

select top 10 Col1,Col2,Col3 from tab1
这让我

(1, 1, 1)
(5, 2, 59)
(8, 3, 69)
(9, 4, 70)
(10, 5, 71)
(11, 6, 72)
(11, 7, 73)
(11, 8, 74)
(11, 9, 75)
(11, 10, 76)
我想把结果浓缩为

    (1, 1, 1)
    (5, 2, 59)
    (8, 3, 69)
    (9, 4, 70)
    (10, 5, 71)
    (11, 6, 72,73,74,75,76)
如何在select查询本身中做到这一点

编辑

请注意,所有列都是int类型。在查询结果中,我不介意第三列是否转换为varchar

编辑


最终,我将查询结果存储在一个数据帧中。使用数据帧是否更容易实现这一点?

您可以使用以下技术实现这一点。注意,我以可消费的格式发布了ddl和示例数据。你将来应该自己做这件事

if OBJECT_ID('tempdb..#something') is not null
    drop table #something

create table #something
(
    Col1 int
    , Col2 int
    , Col3 int
)

insert #something
select * 
from (Values
(1, 1, 1),
(5, 2, 59),
(8, 3, 69),
(9, 4, 70),
(10, 5, 71),
(11, 6, 72),
(11, 7, 73),
(11, 8, 74),
(11, 9, 75),
(11, 10, 76))x(Col1, col2,col3)

select Col1
    , MIN(Col2) as Col2
    , Stuff((select ',' + cast(Col3 as varchar(4))
        from #something s2
        where s2.Col1 = s.Col1
        for xml path('')), 1,1 , '') as Col3
from #something s
group by Col1

我认为这在单个select查询中是不可能的,因为select查询对所有行都有一组确定的返回列。所以我需要创建一个临时表吗?在python的数据框架中这样做会更容易吗?@RenéVogt这可以使用XML路径技术在一个查询中完成。您是否希望
(11,6,'72,73,74,75,76')
将这些字符串组合在一个字符串中?不确定为什么会进行否决,但这种事情在这里已经做了数百次了。:)varchar需要足够长才能保存int值。我不知道你的实际数据中有什么值。从您的示例中,它需要至少为2,但我选择了4,它将处理高达9999的值。请随意调整该大小以满足您的实际数据需求。