if else条件使用sql查询

时间:2017-07-06 07:36:54

标签: sql

我有问题为下表生成SQL查询。 这是我的表:

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 1     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

我想成为这样的结果

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 2     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

方案是如果指定是促销,则使用显示和库存数据。 如果指定来自Merchandiser,请使用Promoter for Stock数据中的数据 我怎样才能实现这一目标?

4 个答案:

答案 0 :(得分:2)

Select a.Country, a.Store
, Stock = CASE WHEN a.Designation = "Merchendiser" THEN b.Stock ELSE a.Stock
, Display = CASE WHEN a.Designation = "Merchendiser" THEN b.Display ELSE a.Display
, a.Designation
FROM YourTable a LEFT JOIN YourTable b WHERE b.Designation = "Promoter"

可以做到这一点。目前无法测试。

编辑:我看到你没有说明你使用的是哪个SQL(即SQL服务器,MySQL,PostgreSQL等,所以取决于这个解决方案可能无法运行)。

答案 1 :(得分:2)

试试这个

SELECT County, 
           Store , 
           (CASE WHEN (Designation = 'Merchandiser') THEN (SELECT SUM(STOCK) FROM TABLE WHERE County = County AND Designation = 'Promoter' GROUP BY County) ELSE STOCK END) AS "stock",
           Display, 
           Designation
FROM table

此请求为您提供所需的结果。

答案 2 :(得分:2)

我认为你期待像这样的查询


    Select a.Country, a.Store
    , (CASE WHEN a.Designation = "Merchendiser" THEN (select  Top 1 b.Stock from YourTable b where b.Designation = "Promoter" and b.Country = a.Country and b.Store = a.Store order by id desc) ELSE a.Stock) as Stock
    , a.Display
    , a.Designation
    FROM YourTable a WHERE b.Designation = "Promoter"

答案 3 :(得分:2)

请尝试使用以下代码创建临时表

--===== If the test table already exists, drop it
 IF OBJECT_ID('TestDB..#mytable','U') IS NOT NULL
     DROP TABLE #mytable
 --===== Create the test table with 
 CREATE TABLE #mytable 
        (
        Country varchar(20),
        Store varchar(20),
        Stock int,
        Display varchar(5),
        Designation varchar(20)
        )
   --===== Insert the test data into the test table
 INSERT INTO #mytable 
       (Country, Store, Stock, Display, Designation)


 SELECT 'SG','a','2','YES','Merchandiser' UNION ALL
 SELECT 'SG','a','4','YES','Promoter' 

现在使用以上查询

SELECT Country, 
       Store , 
       (CASE WHEN (Designation = 'Merchandiser') THEN (SELECT SUM(STOCK) FROM #mytable WHERE Country = Country AND Designation = 'Promoter' GROUP BY Country) ELSE STOCK END) AS "stock",
       Display, 
       Designation FROM #mytable
相关问题