如何将来自不同列的多个列组合到一个表或视图中?

时间:2015-08-01 15:46:06

标签: sql sql-server database sql-server-2008

我有一张商店ID及其销售表。结构就像

商店

>m  <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2) 
>df <- data.frame(col_1 = "abc", col_2 = rep(0, nrow(m))) 
>df 
 col_1 col_2 
1  abc   0 
2  abc   0 

>df$col_2 <- m 
>df 
  col_1 col_2.1 col_2.2 
1   abc       1       3 
2   abc       2       4 

我希望得到以下格式的结果:

Shop_id (int)  |  Sell (time)

我通过以下查询获得特定日期的销售。

Shop Id, Monday sales, Tuesday sales, ....., Sunday Sales.

但在那之后,我无法将其结合起来。 我尝试了不同的连接,但重复结果而不是放置null。 我尝试了以下查询,但它无法正常工作。

declare @day table( id int, sale time)

INSERT INTO @day ( id,sale) 
SELECT   s.Shop_id as id ,s.sell as sale 
FROM Shops as s left join Shops as s2 on s.[Shop_id] = s2.[Shop_id]

如果有其他方法可以合并,请告诉我。

输出结果应如下所示。

每周销售

SELECT ( SELECT sale FROM @day1 )as MONDAY,( SELECT sale FROM @day2 ) as TUESDAY 

2 个答案:

答案 0 :(得分:2)

有几种方法可以执行此操作,您可以使用嵌套查询作为您提供的示例,但您需要添加WHERE子句以获取每一天。您是否想要获得当天的总销售额?你甚至可能不需要“day”表,你可以运行查询来为每天提供SUM(),这是一个例子:

SELECT
(SELECT SUM(sale) FROM Shops
   WHERE Shop_id = [SHOP_ID]
   AND Sell = [mm/dd/yyyy) AS monday,
   ... AS tuesday, ...,

每天都要这样做才能度过余下的日子。您可能需要调整查询,我正在处理有关您项目的有限知识和信息。

我要看的另一件事是写一个“数据透视表”准备声明。通过这种方式,您可以轻松地使用它并将所需的参数传递给它并获得结果。

答案 1 :(得分:1)

我们为您解答@ParekhAbhishekN

SELECT Shop_id, [Monday], [Tuesday], [Wednesday], [Thursday], [Friday],    [Saturday], [Sunday]
FROM (
SELECT Shop_id, DATENAME(dw, sell) AS DayWeek,convert(time,sell) time_,Shop_id id,ROW_NUMBER() over(Order by shop_id) r_num
FROM Shops
) AS src
pivot (
MAX(time_) FOR DayWeek IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday])
) AS pvt