2017-05-05 20 views
2
category Item Price 
    A  Pen  NULL 
    B  Pen  10 
    A  Pencil 10 
    B  Pencil 8 
    C  Pencil 7 
    A  Note Book 40 
    B  Note Book 30 
    C  Note Book 20 
    A  Bottle NULL 
    B  Bottle 80 
    A  Ball 50 
    B  Ball 40 
    A  Bag  1000 
    B  Bag  800 

這是我的數據,我想只顯示A類數據,如果A的價格爲null 然後顯示B類的價格。我試過,但不知道我是如何顯示 數據如何使用情況後,凡在SQL Server的條款

select * from tbl1 
where category = case when price is null then 'B' else 'A' end 

當運行這個查詢是隻顯示A類數據

category Item Price 
A   Pencil 10 
A   Note Book 40 
A   Ball  50 
A   Bag  1000 
+1

輸出應該如何? –

+0

你到目前爲止嘗試過什麼? –

回答

0

使用left joincoalesce()(你也可以使用isnull()):

select a.Category, a.Item, coalesce(a.Price,b.Price) as Price 
from yourtable a 
    left join yourtable b 
    on a.Item = b.Item 
    and b.category = 'B' 
where a.category = 'A' 

coalesce()將返回第一個非null值從參數按順序從左到右。

rextester演示:http://rextester.com/FZO89906

回報:

+----------+-----------+-------+ 
| Category | Item | Price | 
+----------+-----------+-------+ 
| A  | Pen  | 10 | 
| A  | Pencil | 10 | 
| A  | Note Book | 40 | 
| A  | Bottle | 80 | 
| A  | Ball  | 50 | 
| A  | Bag  | 1000 | 
+----------+-----------+-------+ 

參考:

1

像這樣

SELECT price 
FROM table 
WHERE 
    category = CASE 
      WHEN price is not null THEN 'A' 
      ELSE 'B' 
      END 

`

+0

這裏的問題在於,當考慮「B」行時,他們試圖對「A」行進行「推理」。當考慮是否在結果中包含「B」行時,他們希望'價格'列的值來自'A'行。它不能用一個簡單的'WHERE'條件來完成。 –

0
;WITH cte(category,Item,Price) 
AS 
(
SELECT 'A','Pen'  ,NULL UNION ALL 
SELECT 'B','Pen'  ,10 UNION ALL 
SELECT 'A','Pencil' ,10 UNION ALL 
SELECT 'B','Pencil' ,8  UNION ALL 
SELECT 'C','Pencil' ,7  UNION ALL 
SELECT 'A','Note Book' ,40 UNION ALL 
SELECT 'B','Note Book' ,30 UNION ALL 
SELECT 'C','Note Book' ,20 UNION ALL 
SELECT 'A','Bottle' ,NULL UNION ALL 
SELECT 'B','Bottle' ,80 UNION ALL 
SELECT 'A','Ball'  ,50 UNION ALL 
SELECT 'B','Ball'  ,40 UNION ALL 
SELECT 'A','Bag'  ,1000 UNION ALL 
SELECT 'B','Bag'  ,800 
) 
SELECT category,Item,Price From 
(
SELECT *,ROW_NUMBER()Over(Partition by Price order by Price)seq From 
(
SELECT o.* FROM cte i 
INNER JOIN cte o 
ON o.category=i.category 
WHERE o.category='A' AND o.Price!=i.Price 
)dt 
) Final 
where Final.seq=1 

輸出

category Item Price 
A   Pencil 10 
A   Note Book 40 
A   Ball  50 
A   Bag  1000 

輸出對於value'B」

category Item  Price 
-------------------------------- 
B   Pencil  8 
B   Pen   10 
B   Note Book 30 
B   Ball  40 
B   Bottle  80 
B   Bag   800 
0

我把它理解爲如果在一個項目類別有一個零價格它應該從另一個類別拿起具體項目有價格

--Filter records having prices 
with CTETable as 
(
Select distinct category, item, price 
from tbl1 
where price is not null 
) 
--distinct items 
select * from 
(select category, item, price, ROW_NUMBER() over (Partition by Item order by 
Category) as RowNo from CTETable) 
as c 
where c.RowNo=1