并排选择语句结果

时间:2015-02-18 21:29:55

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

我要做的是将两个select语句(应始终具有相同数量的行和列)并排组合,而不是将它们一起添加。我试过的是union all

SELECT Name,Price As 'Monday' FROM tbl_checktable WHERE (Type = 3042) And CloseDate = '2015-02-09'
Union All
SELECT Name,Price As 'Tuesday' FROM tbl_checktable WHERE (Type = 3042) And CloseDate = '2015-02-10'

但是当然我把它们组合成线性的

Name | Monday

Name | Value

Name | Value

我想要实现的是这个

Name | Monday | Tuesday

Name | Value | Value

编辑:当星期一没有相应的值时,如何避免星期二被删除的结果?

SELECT m.Name, m.Price AS 'Monday', t.Price as 'Tuesday', w.Price as 'Wed'
   FROM tbl_checktable m 
LEFT JOIN tbl_checktable t on m.name = t.name 
LEFT JOIN tbl_checktable w on m.name = w.name 
   WHERE (m.Type=3042 ) AND m.CloseDate ='2015-02-09'
    AND  (t.Type=3042 ) AND t.CloseDate='2015-02-10'
    AND  (w.Type=3042 ) AND w.CloseDate='2015-02-11'

5 个答案:

答案 0 :(得分:4)

我认为PIVOT最适合您要解决的问题:

SELECT Name, 
       [2015-02-09] AS Monday, [2015-02-10] AS Tuesday, [2015-02-11] AS Wednesday
FROM (
   SELECT Name, Price, CloseDate 
   FROM tbl_checktable
   WHERE Type = 3042) AS SourceTable
PIVOT
(
   AVG(Price)
   FOR CloseDate IN ([2015-02-09], [2015-02-10], [2015-02-11])
) AS PivotTable;

SQL Fiddle Demo here

答案 1 :(得分:2)

它可以解决问题:

SELECT *
FROM
(
    SELECT Name, Price, DATENAME(WEEKDAY, CloseDate) as dayn
    FROM tbl_checktable 
    WHERE [Type] = 3042
    AND CloseDate IN ('02/16/2015', '02/17/2015') 
) d
PIVOT
(
    MAX(Price) for dayn IN (Monday, Tuesday)
) piv;

根据您的需要添加星期三,星期四等

答案 2 :(得分:1)

您必须使用JOIN而不是UNION。

SELECT m.Name, m.Price AS 'Monday', t.Price as 'Tuesday'
   FROM tbl_checktable m OUTER JOIN tbl_checktable t on m.name = t.name 
   WHERE m.Type=3042 AND m.CloseDate ='2015-02-09'
    AND  t.Type=3042 AND t.CloseDate='2015-02-10';

答案 3 :(得分:0)

只需使用case声明:

SELECT Name,case CloseDate  
when '2015-02-09' then Price else null end As Monday,
case CloseDate  
when '2015-02-10' then Price else null end As Tuesday
 FROM tbl_checktable WHERE (Type = 3042) and CloseDate  in ('2015-02-09','2015-02-10')

答案 4 :(得分:0)

我认为这符合您的要求,但我认为有更好的方法来解决这个问题。

SELECT
   min(case when m.CloseDate = '2015-02-09' then m.Price else null end) as Monday,
   min(case when m.CloseDate = '2015-02-10' then t.Price else null end) as Tuesday,
   min(case when m.CloseDate = '2015-02-11' then w.Price else null end) as Wednesday
   FROM tbl_checktable m, tbl_checktable t, tbl_checktable w
   WHERE
         m.Type = 3042 AND m.CloseDate = '2015-02-09'
     AND t.Type = 3042 AND t.CloseDate = '2015-02-10'
     AND w.Type = 3042 AND w.CloseDate = '2015-02-11'

你真的不需要这些联接,我也想知道你为什么离开联盟:

SELECT
   min(case when m.CloseDate = '2015-02-09' then m.Price else null end) as Monday,
   min(case when m.CloseDate = '2015-02-10' then m.Price else null end) as Tuesday,
   min(case when m.CloseDate = '2015-02-11' then m.Price else null end) as Wednesday
FROM tbl_checktable as m 
WHERE
        m.Type = 3042
    AND m.CloseDate IN ('2015-02-09', '2015-02-10', '2015-02-11')