想象一下,我们有一个表格,如:
Number Value GroupValue
1 FOO GR1
22 BAR GR2
100 FOO3 GR1
20 BAR23 GR2
我想根据组值获取这些行的总和值,但是,我想看看它在另一列中分组的行,例如:
SUM values groups
101 FOO,FOO3 GR1
42 BAR,BAR23 GR2
我如何在sql中实现这一目标?
尝试:
> SELECT SUM(ID) AS SUM ,
STUFF(( SELECT ',' + A
FROM dbo.Table_1 AS T2
WHERE A = T2.A
FOR
XML PATH('')
), 1, 1, '') AS A ,
B
FROM dbo.Table_1 AS T
GROUP BY B ,
A
但这无法正确处理这些群体......
答案 0 :(得分:1)
您无法使用SELECT
中GROUP BY
列表中创建的别名。
您可以通过将列表与聚合(cte / subquery)分开来解决此问题:
WITH cte AS (SELECT *
,STUFF(( SELECT ',' + Value
FROM Table1 AS T2
WHERE T.GroupValue = T2.GroupValue
FOR XML PATH('')
), 1, 1, '') AS Value_List
FROM Table1 AS T)
SELECT SUM(Number) AS Total
,Value_List
,GroupValue
FROM cte
GROUP BY Value_List, GroupValue
演示:SQL Fiddle
或者您可以使用分区SUM()
(窗口函数):
SELECT DISTINCT SUM(Number) OVER(PARTITION BY GroupValue) AS Total
,STUFF(( SELECT ',' + Value
FROM Table1 AS T2
WHERE T.GroupValue = T2.GroupValue
FOR XML PATH('')
), 1, 1, '') AS Value_List
,GroupValue
FROM Table1 AS T
演示:SQL Fiddle
答案 1 :(得分:0)
您只需进行一些小改动,将您的SQL 不带组合到该组的另一个选择中。我认为我正确地转换了你的SQL:
SELECT SUM(ID) as IdSum, B FROM (
SELECT ID,
STUFF(( SELECT ',' + A
FROM dbo.Table_1 AS T2
WHERE A = T2.A
FOR
XML PATH('')
), 1, 1, '') AS B
FROM dbo.Table_1 AS T) AS B2
GROUP BY B
答案 2 :(得分:0)
您可以将列表深度嵌套一层
...
SELECT
IDList1=
SUBSTRING((
SELECT ', ' + CAST(TargetID AS NVARCHAR(10))
FROM
(
SELECT
DISTINCT TargetID
FROM
TargetTable
WHERE
TargetIDTableField2=MAINQUERYALIAS.TargetIDTableField2
)
AS UP2
ORDER BY
TargetID FOR XML PATH( '' )
), 3, 1000 )
FROM
(
...
) AS MAINQUERYALIAS
答案 3 :(得分:0)
下载并运行此脚本http://groupconcat.codeplex.com/releases/view/106409 你可以像解决这个问题一样解决你的问题
select SUM(Number), dbo.GROUP_CONCAT(Value)
from Table_2
group by GroupValue
如果这个回答你的问题,请标记为已回答