在SQL Server中选择与GROUP BY不同的字段

时间:2013-05-10 18:46:49

标签: sql-server group-by sap

我正在尝试在SQL Server中运行查询,其中我选择的列与它的分组方式不同。此查询用于SAP。

问题是,如果我按所选的所有相同列进行分组,则不会对任何内容进行分组。

这是我的查询(显然不起作用)。

SELECT 
   T0.[CardCode], T2.[SlpName] as 'Rep', 
   T0.[CardName] as 'Facility', 
   T1.[Address] as 'Attention', 
   T1.[Street] as 'Address 1', 
   T1.[Block] as 'Address 2', T1.[City] as 'City', 
   T1.[State] as 'State', 
   T1.[ZipCode] as 'Zip' 
FROM OCRD T0 
INNER JOIN CRD1 T1 ON T0.[CardCode] = T1.[CardCode] 
INNER JOIN OSLP T2 ON T2.[SlpCode] = T0.[SlpCode] 
WHERE T1.[State] = 'FL' 
GROUP BY T0.[CardCode]

任何反馈都将不胜感激。

谢谢,

2 个答案:

答案 0 :(得分:0)

你可以尝试这样......

Select CardCode,Rep, 
    Facility, 
    Attention, 
    Address 1, 
    Address 2,City, 
    State, 
    Zip from  (SELECT Row_Number() Over(Partition By T0.[CardCode] order by T0.[CardCode]) as Row,
    T0.[CardCode], T2.[SlpName] as 'Rep', 
    T0.[CardName] as 'Facility', 
    T1.[Address] as 'Attention', 
    T1.[Street] as 'Address 1', 
    T1.[Block] as 'Address 2', T1.[City] as 'City', 
    T1.[State] as 'State', 
    T1.[ZipCode] as 'Zip' 
    FROM OCRD T0 
    INNER JOIN CRD1 T1 ON T0.[CardCode] = T1.[CardCode] 
    INNER JOIN OSLP T2 ON T2.[SlpCode] = T0.[SlpCode] 
    WHERE T1.[State] = 'FL' 
    ) a where row=1

答案 1 :(得分:0)

如果你真的不在乎哪个值返回。这是一个例子

SELECT 
   T0.[CardCode], 
   T2.[SlpName] as 'Rep', 
   T0.[CardName] as 'Facility', 
   T1.[Address] as 'Attention', 
   T1.[Street] as 'Address 1', 
   T1.[Block] as 'Address 2', T1.[City] as 'City', 
   T1.[State] as 'State', 
   T1.[ZipCode] as 'Zip' 
FROM OCRD T0 
CROSS APPLY (SELECT TOP 1 * FROM CRD1 TT1 ON T0.[CardCode] = TT1.[CardCode] AND TT1.[State] = 'FL') T1
CROSS APPLY (SELECT TOP 1 * FROM OSLP TT2 ON TT2.[SlpCode] = T0.[SlpCode]) T2