SQL获得多个结果到一个单元格?
问题描述:
所以我正在运行一个报告,看看有多少客户向我们下单。我的大部分数据都是他们的电子邮件,他们购买了多少次,他们的姓名,最后一个订单日期和最后一个OrderID。SQL获得多个结果到一个单元格?
我不知道如何得到是从该订单项目获得productCode。
这些项目存储在一个名为Lines的独立表中,并通过OrderID链接到主订单。
有没有一种方法,如果每条订单有多条线,将这些行中的ProductCodes作为逗号分隔值?
类似的东西
BuyerEmail | HowMany | Name | ProductCodes
--------------------------------------------
[email protected] | 12 | Bud | 1231, 123,
这个查询将更好地解释它...:
SELECT TOP 1000
o.BuyerEMail
,COUNT(*) HowMany
,o.Name
,o2.OrderID
FROM Orders o
JOIN
(
SELECT
BuyerEmail
,MAX(OrderDate) Latest
FROM Orders
GROUP BY BuyerEmail
) l
ON o.BuyerEmail = l.BuyerEmail
JOIN Orders o2
ON l.BuyerEmail = o2.BuyerEmail
AND l.OrderDate = o2.OrderDate
WHERE Pay != 'PayPal'
GROUP BY
o.BuyerEmail
,o.Name
,l.Latest
ORDER BY
COUNT(*) DESC
是否有可能来连接细胞? 我只是不知道从哪里开始。
谢谢
答
当然,这是可能的,你需要做这样的事情:
select NId_Lista_Surtido,
stuff((select cast(',' as varchar(max))+ cast(nid_detalle_surtido as varchar(max)) <<<--- this is the value being appended
from CES_DLista_Surtido dsurtido <-- this is the detail table
where dsurtido.nid_lista_surtido=tsurtido.nid_lista_surtido <-- this is the condition
for xml path('')),1,1,'') as prueba <-- this is how the col name.
from CES_TLista_Surtido tsurtido <-- this is the main table
,这是ouptput
NId_Lista_Surtido prueba 1 95854,95855,95856,95857,95858,95859,95860,95861,95862,95863,95864,95865,95866,95867,95868,95869,95870,95871,95872,95873,95874,95875,95876
这是一个工作示例有了我的数据,如果你有疑问,问我需要使用的东西。
看看'FOR XML PATH' – adrianm
[模拟SQL Server中的group \ _concat MySQL函数?]可能的副本(http://*.com/questions/451415/simulating-group-concat-mysql-function-in -sql-server) –
[如何使用GROUP BY串联SQL Server中的字符串?](http://*.com/questions/273238/how-to-use-group-by-to-concatenate- strings-in-sql-server) – Morpheus