将两行合并为一行

时间:2012-12-14 10:08:26

标签: sql-server-2008 stored-procedures

当我运行以下写入的过程时,我得到的返回结果集就像

My Result Set

Result Set 2 但实际上根据场景,我想要的是我想要针对@ContractId参数的单个记录。所以,我想合并我的结果集返回的行。

PS:此图像仅显示少数列,还存在其他一些具有不同值的列。

这是我的程序:

ALTER PROCEDURE [dbo].[sp_Tbl_Contract_SearchOne]
    -- Add the parameters for the stored procedure here
    @ContractID int
AS
BEGIN

    select  
    tbl_Contract.ContractID,
    KeyWinCountNumber, 
    ItemName,
    BrandName,
    CountName,
    SellerName,
    BuyerName,
    ContractNumber,
    ContractDate,
    CountryFromName,
    CountryToName,
    TotalQty,
    Vans,
    UnitPrice,
    Amount
    from tbl_Contract

    inner join tbl_CountDetail
    on
    tbl_CountDetail.ContractID = Tbl_Contract.ContractID
    inner join tbl_Count tcount
    on
    tcount.CountID = tbl_CountDetail.CountID
    INNER JOIN Tbl_Item
    on Tbl_Contract.ItemID = Tbl_Item.ItemID 
    INNER JOIN Tbl_Brand
    on Tbl_Contract.BrandID = Tbl_Brand.BrandID
    INNER JOIN Tbl_Seller
    on Tbl_Contract.SellerID = Tbl_Seller.SellerID
    INNER JOIN Tbl_Buyer 
    on Tbl_Contract.BuyerID = Tbl_Buyer.BuyerID
    INNER JOIN Tbl_CountryFrom
    ON Tbl_Contract.CountryFromID=Tbl_CountryFrom.CountryFromID
    INNER JOIN Tbl_CountryTo 
    ON Tbl_Contract.CountryToID = Tbl_CountryTo.CountryToID
    inner join tbl_CostUnit
    on Tbl_Contract.CostUnitID = tbl_CostUnit.CostUnitID    
    where Tbl_Contract.ContractID = 1
    and Tbl_Contract.IsDeleted = 0 and tbl_CountDetail.IsDeleted = 0
END

2 个答案:

答案 0 :(得分:1)

这取决于你想用CountName字段做什么(两者之间唯一不同的值)但理论上你可以使用GROUP BY(如果你排除CountName)或者如果你使用{想要包含CountName,那么也许PIVOT可以完成这项工作。

答案 1 :(得分:1)

这属于聚合,通常聚合意味着对要压缩成单行的行执行操作(总和,平均值,标准偏差)。例如,如果您的数据包含每人每天的Cookie销售数量:

day    person    sales
======================
1      Bob       5
1      Jane      8
2      Bob       2
2      Jane      10

您希望查看所有天的每人总销售额,您可以选择personsum(sales)人员分组

select  
   person
   sum(sales)
from salesData
group by person

您的案例不太标准,因为您试图汇总基于字符或字母数字的字段。这样很好,因为有一些聚合可以用于字符字段。 MIN仍然可以正常工作,如MAX - 分别返回第一个和最后一个字段。

即,对mina进行bca将首先返回Amount(按字符串排序规则排序最小值)。您似乎还有其他一些数字字段(UnitPriceTotalQtySUM) - 您可以选择正确的聚合 - 我怀疑select tbl_Contract.ContractID, KeyWinCountNumber, ItemName, BrandName, MIN(CountName) as FirstCountName, SellerName, BuyerName, ContractNumber, ContractDate, CountryFromName, CountryToName, SUM(TotalQty) AS SumTotalQuantity, Vans, SUM(UnitPrice) as TotalUnitPrice, SUM(Amount) AS TotalAmount from tbl_Contract [...snip...] group by tbl_Contract.ContractID, KeyWinCountNumber, ItemName, BrandName, SellerName, BuyerName, ContractNumber, ContractDate, CountryFromName, CountryToName, Vans 很可能是

所以你可以这样做:

FirstCountName

现在将返回1行,其中Count1 502的值为{{1}},因为这是聚合字段的第一个(最小)值。