SQL Server查询不返回所有商店

时间:2015-05-28 12:37:43

标签: sql sql-server

我在圈子里跑来跑去,并且在过去几个小时里一直这样做。

我正在一张桌子上做一个选择,其中包含每个商店的所有库存,我按产品ID过滤。我需要的是:拥有所有商店的清单,即使我没有该商店的数据,但选择只返回4个或更少的商店。

以下是一个例子:

这是查询:

select 
    store_id, product_id, start_date, quantity 
from 
    stock 
where 
    product_id = 407214

结果就是这样:

store_id | product_id |       start_date      | quantity |
    2    |   407214   |  2015-05-26 08:32:53  |    10    |
    3    |   407214   |  2015-03-16 12:10:00  |    25    |
    4    |   407214   |  2015-01-06 11:45:15  |    16    |
    7    |   407214   |  2015-05-14 00:00:00  |    8     |

这就是我想要的:

store_id | product_id |       start_date      | quantity |
    1    |    NULL    |          NULL         |   NULL   |
    2    |   407214   |  2015-05-26 08:32:53  |    10    |
    3    |   407214   |  2015-03-16 12:10:00  |    25    |
    4    |   407214   |  2015-01-06 11:45:15  |    16    |
    5    |    NULL    |          NULL         |   NULL   |
    6    |    NULL    |          NULL         |   NULL   |
    7    |   407214   |  2015-05-14 00:00:00  |    8     |

我真的需要帮助,这让我发疯了!

5 个答案:

答案 0 :(得分:5)

解决方案取决于您的数据库结构

如果Derived表仅包含可用产品,则需要stock个表left joinstores

stock

答案 1 :(得分:3)

OR product_id IS NULL添加到WHERE子句

答案 2 :(得分:0)

sed -i 's/p2p_oper_channel=[0-9]\\+/p2p_oper_channel=x/' /data/misc/wifi/p2p_supplicant.conf 将返回没有值的行。 Is null子句中的or用于条件。如果特定行表示这些条件之一。

where

或者你的null是一个字符串?

select store_id, product_id, start_date, quantity 
     from stock where 
          product_id = 407214 OR Product_id iS null

或许你输入的product_id为null你可以试试这个:

 select store_id, product_id, start_date, quantity 
     from stock where 
          product_id = 407214 OR Product_id like null

或许如果你想要一切,删除select store_id, product_id, start_date, quantity from stock where product_id = 407214 OR Product_id = null 条款,但你按product_id订购:(也许这就是你的意思)

where

答案 3 :(得分:0)

select store_id, product_id, start_date, quantity from stock where product_id = 407214 or product_id = null

答案 4 :(得分:0)

知道如何generate fixed number of rows in a table你可以:

--select 5 as store_id, 407214 as product_id, 3 as start_date, 3 as quantity into stock

DECLARE @maxStoreId int
SELECT 
    @maxStoreId = MAX(store_id) 
FROM 
    stock;

WITH r AS (
    SELECT 1 AS n
    UNION ALL
    SELECT n+1 FROM r WHERE n+1<=@maxStoreId
)
SELECT 
    r.n as store_id, product_id, start_date, quantity  
FROM 
    r left outer join stock on  r.n = stock.store_id
WHERE 
    product_id = 407214 or product_id is null

--drop table stock