select C.customerId,(C.lastName+', '+C.firstName) as CustomerName, C.companyName,
D.companyName+' ('+D.lastName+','+D.firstName+')'
as "Parent CompanyName(Last, First)",S.siteId, S.nickName as siteName,
dbo.GetSiteTelemetryBoxList(s.siteId) as "DeviceId's",
dbo.GetSiteTelemetryBoxSKUList(S.siteId,0) as SKU
from Site S
INNER JOIN Customer C ON S.customerId = C.customerId
INNER JOIN Customer D ON D.customerId = C.parentCustomerId
where S.createDate between DATEADD(DAY, -65, GETUTCDATE()) and GETUTCDATE()
order by C.customerId, S.siteId
上面的查询返回如下所示的值:
CID CustomerName companyName Parent CompanyName(Last, First) SiteName DeviceId SKU
888296 DeYoung, Scott DeYoung Farms Mercier Valley Irrigation (Mercier,Ralph) H E east 200241 NETB12WR
890980 Rust, Marcus NULL Chester Inc. (Young,Scott) Byroad east 346370 NETB12WR
890980 Rust, Marcus NULL Chester Inc. (Young,Scott) Byroad west 345431 NETB12WR
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) hwy 64 south 333721 UNKNOWN
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) HWY 64 North 250162 NETB12WR
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) HWY 64 West 250164 NETB12WR
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) HWY 64 East 250157 NETB12WR
891430 Gammil, Bob Gammil FArms AMX Irrigation (Burroughs,Michael) angel 333677 UNKNOWN
891430 Gammil, Bob Gammil FArms AMX Irrigation (Burroughs,Michael) cemetery 333564 UNKNOWN
我现在面临的问题是,如果customerId / Name在结果集中重复。应连接SiteName,deviceId,SKU以将数据表示为一个值。 例如,Mark Pirani行看起来像
CID CustomerName ... SiteName DeviceId's ...
891904 Pirani, Mark ... hwy 64 south, HWY 64 North, HWY 64 West, HWY 64 East 333721,250162,250164,250157 ...
答案 0 :(得分:0)
您可以使用类似的内容转换行,将行转换为连续字符串:
select
distinct
stuff((
select ',' + u.username
from users u
where u.username = username
order by u.username
for xml path('')
),1,1,'') as userlist
from users
group by username
答案 1 :(得分:0)
我认为这比SQL
代码问题更多是C#
查询问题,或者更合适我认为在查询级别而不是代码级别解决此问题更有效。在我的头顶,你可以使用SELECT DISTINCT
或GROUP BY
条款。
以下是解决此问题的另一个StackOverflow问题 - How do I (or can I) SELECT DISTINCT on multiple columns?
答案 2 :(得分:-1)
我做了一些挖掘,并找到了一些方法来实现它。基本上,对此的简单解决方案是使用mysql的group_concat函数。这些链接讨论了如何为SQL Server实现group_concat。您可以根据自己的要求选择一个。