ASP / SQL:将数据分组到列

时间:2017-03-08 09:23:40

标签: c# sql asp.net sql-server

我有一个观点,我在不同月份对客户和公司进行分组,因此我总共只有一个客户/公司。

我想要做的是将所有月份的所有客户(已分组)和列Money放入一个新表中,其中Months(Money)是列。我怎么能在SQL中这样做?因此,也许客户xy在1月份有1个钱,但在2月份可能会获得NULL等等......

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为它是一个简单的连接,如下所示:

DECLARE @Customer TABLE (ID int, Name varchar(100))
DECLARE @January TABLE (CustomerId int, Money decimal)
DECLARE @February TABLE (CustomerId int, Money decimal)
DECLARE @March TABLE (CustomerId int, Money decimal)

INSERT INTO @Customer (id, name) VALUES (1, 'C1')
INSERT INTO @Customer (id, name) VALUES (2, 'C2')
INSERT INTO @Customer (id, name) VALUES (3, 'C3')

INSERT INTO @January (CustomerId, Money) VALUES (1, 500)
INSERT INTO @January (CustomerId, Money) VALUES (2, 300)

INSERT INTO @February (CustomerId, Money) VALUES (2, 100)
INSERT INTO @February (CustomerId, Money) VALUES (3, 200)

INSERT INTO @march (CustomerId, Money) VALUES (1, 700)
INSERT INTO @march (CustomerId, Money) VALUES (2, 600)

SELECT DISTINCT c.*, j.Money as Money_January, f.Money as Money_February, m.Money as Money_March 
FROM @Customer c
LEFT JOIN @January j ON c.Id = j.CustomerId
LEFT JOIN @February f ON c.Id = f.CustomerId
LEFT JOIN @March m ON c.Id = m.CustomerId