我有一个表my_table,其中包含列州,月,ID和销售。
我的目标是将具有相同状态,月份,ID的不同行合并为一行,同时将这些选定行的销售列汇总到合并行中。
例如:
state month ID sales
-------------------------------
FL June 0001 12,000
FL June 0001 6,000
FL June 0001 3,000
FL July 0001 6,000
FL July 0001 4,000
TX January 0050 1,000
MI April 0032 5,000
MI April 0032 8,000
CA April 0032 2,000
这就是我应该得到的
state month ID sales
-------------------------------
FL June 0001 21,000
FL July 0001 10,000
TX January 0050 1,000
CA,MI April 0032 15,000
答案 0 :(得分:2)
您需要使用GROUP_CONCAT
:
SELECT GROUP_CONCAT(DISTINCT State) AS State
, Month, ID, SUM(Sales)
FROM Table1
GROUP BY Month, ID;
对于SQL Server,您可以使用STUFF()
:
SELECT state =
STUFF((SELECT DISTINCT ' , ' + state
FROM Table1 b
WHERE b.ID = a.ID
AND b.month = a.month
FOR XML PATH('')), 1, 2, '')
,month, ID, SUM(sales) AS Sales
FROM Table1 a
GROUP BY month,ID;
答案 1 :(得分:1)
请试试这个:
SELECT B.STATE, A.ID, SUM(A.SALES) AS SALES
FROM MYTABLE A
INNER JOIN
(SELECT DISTINCT
CASE WHEN A.state = B.STATE THEN A.STATE ELSE A.STATE+','+B.STATE END AS STATE,
ID
FROM MYTABLE A
INNER JOIN MYTABLE B ON A.ID = B.ID) B
ON A.STATE = B.STATE
GROUP BY B.state, A.month, A.ID
如果查询需要任何纠正,请告诉我。
答案 2 :(得分:0)
您实际想要做的是分组而不是合并行。 在聚合不同值的同时将具有共同值的多个行分组。
使用Group By子句来实现上述目的:
select state,month,ID sum(sales)
from my_table
group by
state, month, ID
点击此处了解有关群组的更多信息:http://www.w3schools.com/sql/sql_groupby.asp