在不同的列中显示查询结果
Have Query Results Display In Different Columns
我试图避免创建 table 来显示这些结果(如果可能)。我想要做的是基本上让我的查询结果看起来像 table,并且有一个用于 fullitemlist 的列,一个用于 'has been ordered' 的列和一个用于 'has not been ordered' 的列。本质上,我正在尝试从我的查询中返回这样的结果集:
> 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 查询,但它 returns 一个巨大列表中的所有内容,而不是我想要的:)
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
-- 你可以根据你的问题这样写你的查询,而不是 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
我试图避免创建 table 来显示这些结果(如果可能)。我想要做的是基本上让我的查询结果看起来像 table,并且有一个用于 fullitemlist 的列,一个用于 'has been ordered' 的列和一个用于 'has not been ordered' 的列。本质上,我正在尝试从我的查询中返回这样的结果集:
> 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 查询,但它 returns 一个巨大列表中的所有内容,而不是我想要的:)
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
-- 你可以根据你的问题这样写你的查询,而不是 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