2012-12-10 72 views
0

我目前擁有的是:在SQL逗號分隔值使用存儲過程

COUNT DETAILS: 
CNT DTLID  COUNT   TOTAL QTY  UNITPRICE   AMOUNT 
1    234     2222   1.20     32 
1    12     123   2      21 


What i want it to be like 
CNT DTLID  COUNT   TOTAL QTY   UNITPRICE   AMOUNT 
1    234,12   2222 , 123  1.20,2    32 + 21 = 53 

我想有逗號分隔值,也希望通過量列子句中使用組。

目前我真的什麼是高達:

ALTER PROCEDURE [dbo].[sp_Tbl_CountDetail_SelectAll] 
    -- Add the parameters for the stored procedure here 

AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 

    select * from Tbl_CountDetail 
    inner join tbl_Contract 
    on 
    tbl_CountDetail.ContractID = tbl_Contract.ContractID 
    inner join tbl_Count 
    on 
    tbl_CountDetail.CountID = tbl_Count.CountID 
    where tbl_CountDetail.isDeleted = 0 
    and tbl_Contract.isdeleted = 0 
END 

回答

0

一些友好的樣本數據

create table #CountDetails 
(
DTLID int, 
CNT int, 
Qty int, 
UnitPrice money, 
Amount int 
) 

insert into #CountDetails 
SELECT 
1, 234, 2222, 1.20, 32 
UNION ALL SELECT 
1, 12, 123, 2, 21 

下面是一些代碼

SELECT 
    DTLIDs.DTLID, 

    CNTs = 
     ISNULL(
      STUFF(
       (
        select ',' + 
         cast(CD.cnt as varchar(50)) 
        from #CountDetails CD 
        where CD.DTLID = DTLIDs.DTLID 
        order by CD.CNT 
        FOR XML PATH('') 
       ), 
       1, 1, '' --removes the leading ',' 
      ), 
      '' 
     ), 

    QTYs = 
     ISNULL(
      STUFF(
       (
        select ',' + 
         cast(CD.qty as varchar(50)) 
        from #CountDetails CD 
        where CD.DTLID = DTLIDs.DTLID 
        order by CD.Qty 
        FOR XML PATH('') 
       ), 
       1, 1, '' --removes the leading ',' 
      ), 
      '' 
     ), 

    UnitPrices = 
     ISNULL(
      STUFF(
       (
        select ',' + 
         cast(CD.UnitPrice as varchar(50)) 
        from #CountDetails CD 
        where CD.DTLID = DTLIDs.DTLID 
        order by CD.UnitPrice 
        FOR XML PATH('') 
       ), 
       1, 1, '' --removes the leading ',' 
      ), 
      '' 
     ), 

    AmountSum = 
    (
     select SUM(Amount) from #CountDetails CD 
     where CD.DTLID = DTLIDs.DTLID 
    ) 

from (
    select distinct DTLID from #CountDetails 
    ) DTLIDs 

有不同的方法來調整這一點。例如,「AmountSum =」嵌套查詢代碼可以在一個組上完成 - 我就像給出查詢其餘部分的結構方式時的一致外觀一樣。

對於CSV列表,您沒有指定如何分類。我已經按值排序(例如ORDER BY CD.CNT),但您可以通過任何您想要的順序更改它。同樣,CSV值之間沒有空格。你可以通過改變選擇','來調整它,在那裏有一個空間和STUFF命令的參數(將第二個1改爲2)。

基本上,FOR XML PATH('')位取其小寫結果集並返回一些沒有XML文本的文本(由於'')。在XML PATH結果開始時,使用STUFF來清除前導。

希望這會有所幫助! :)

+0

您提供的select語句似乎與您提供的示例數據不符。我在回答問題時忽略了您的查詢...請進行翻新以適應。 –

+0

這是存儲過程還是函數? 我必須爲此寫一個函數嗎? –

0

可以做這樣的事情....

DECLARE @VALUES NVARCHAR(1000),@UnitPrice nvarchar(100) 
SELECT @VALUES = COALESCE(@VALUES + ',','') + CAST(COUNTQty AS NVARCHAR(50)), 
@UnitPrice = COALESCE(@UnitPrice + ',','') + CAST(UnitPrice AS NVARCHAR(50)) FROM tableName 
SELECT @VALUES as [CountQty],@Ids as [UnitPrice] 

有沒有價格問題檢查組.. !!

相關問題