查询结果显示在不同的列中

时间:2015-05-22 11:49:37

标签: sql-server-2008 pivot

我正在尝试避免创建表以显示这些结果(如果可能)。我想要做的是基本上看看我的查询结果的表格,并有一个fullitemlist列,已经订购了一列'还没有订购'的列。基本上我正在尝试从我的查询中返回一个像这样的结果集:

> Zip = 55555
> fullitemlist ----- Has Been Ordered ---- Has Not Been Ordered
> Knife Set              1                      0
> Butcher Block          0                      1
> Dishwasher             0                      1
> Hair Dryer             1                      0

依此类推我的tbl_itemlist中的所有项目。这是我尝试使用的3个CTE查询,但它返回一个巨大的列表中的所有内容,而不是我之后的内容:)

Declare @zip varchar(5)
Set @zip = '55555'
;With CTE As
(
  Select fullitemlist from tbl_ItemList
  Where zip = @zip
)
,CTE2 As
(
  Select case when hasbeenordered = 1 then 1 else 0 end as 'Has Been Ordered' from tbl_purchasehistory
  WHERE itemid IN (Select itemid from tbl_ItemList where hasbeenordered = 1   and zip = @zip)
)
,CTE3 As
(
  Select case when hasbeenordered = 0 then 1 else 0 end as as 'Has NEVER Been Ordered' from tbl_purchasehistory
  WHERE itemid IN (Select itemid from tbl_ItemList where hasbeenordered = 0 and zip = @zip)
)

SELECT * from CTE
UNION ALL
SELECT * FROM CTE2
UNION ALL
SELECT * FROM CTE3

1 个答案:

答案 0 :(得分:2)

- 你可以根据你的问题而不是CTE ,union all,SubQuery来编写这样的查询,这是最简单的方法。

SELECT fullitemlist
    ,CASE 
        WHEN tp.hasbeenordered = 1
            AND tI.hasbeenordered = 1
            THEN 1
        ELSE 0
        END AS 'Has Been Ordered'
    ,CASE 
        WHEN tp.hasbeenordered = 0
            AND ti.tp.hasbeenordered = 0
            THEN 1
        ELSE 0
        END AS 'Has NEVER Been Ordered'
FROM tbl_ItemList ti
INNER JOIN tbl_purchasehistory tp ON ti.itemid = tp.ItemId
WHERE zip = @zip