SQL-将值从一列拆分为两列

时间:2018-09-12 18:59:57

标签: sql sql-server

我试图获取“数量”列的值并将“数量”小于500的值分割开,然后将这些记录放入LessThan500列中,对于大于500的记录放入“ GreaterThan500”列中。 我有一个执行此操作的select语句,但是表没有正确更新

SUM(CASE WHEN Quantity < 500 THEN CAST(( Quantity*10 ) AS INT)
                 ELSE ''
            END) as Quantityx10
, SUM(CASE WHEN Quantity < 500 THEN CAST(( Quantity*10 ) AS INT)
                 ELSE ''
            END) AS '<500'
  , '' AS '>=500'


USE FET

-- Create a new template table
IF OBJECT_ID('dbo.FuelSales', 'U') IS NOT NULL 
  DROP TABLE dbo.FuelSales; 

CREATE TABLE FuelSales
(
    TransactionType varchar(1) null,
    TransactionID int,
    CustomerID int null,
    TransactionDate date null,
    EntryTimeofDay datetime null,
    UserTranNumber varchar(15) null,
    AircraftNumber varchar(10) null,
    CompanyName varchar(40) null,
    NumNameCode varchar(30) null,
    Description varchar(40) null,
    Quantity decimal(18,6) null,
    LessThan500 decimal(18, 6) null,
    GreaterThan500 decimal(18,6) null,
);

INSERT INTO FuelSales(TransactionType, TransactionID, CustomerID, TransactionDate, EntryTimeofDay,UserTranNumber,AircraftNumber,CompanyName,NumNameCode,Description,Quantity,LessThan500,GreaterThan500)
SELECT ci.TransactionType
    , ci.TransactionID
    , ci.CustomerID
    , ci.TransactionDate
    , ci.EntryTimeofDay
    , ci.UserTranNumber
    , d.AircraftNumber
    , c.CompanyName
    , d.NumNameCode
    , d.Description
    , Quantity

  FROM [TFBO7].[dbo].[CustInv] ci
  INNER JOIN [TFBO7].[dbo].[Cust] c
  ON c.CustomerID=ci.CustomerID
  INNER JOIN [TFBO7].[dbo].[CustIDet] d
  ON ci.TransactionID=d.TransactionID      
  WHERE ci.TransactionDate between '20180701' and '20180731' and d.TransactionTypeID='1'

2 个答案:

答案 0 :(得分:0)

我不确定您为什么会在表上永久执行此操作,而不仅仅是在需要时将其作为即席查询进行分离,而是假设它是SQL Server,它会变成这样(在INSERT语句中您已经在做):

...
  , Quantity
    -- 500 has to go somewhere so I put it in the first category
  , LessThan500 = CASE WHEN Quantity <= 500 THEN Quantity ELSE NULL END
  , GreaterThan500 = CASE WHEN Quantity > 500 THEN Quantity ELSE NULL END
FROM [TFBO7].[dbo].[CustInv] ci
...

答案 1 :(得分:0)

您可以将计算列添加到表中。只要做:

alter table fuelsales add lessthan500 as (case when quantity <= 500 then quantity end);
alter table fuelsales add greaterthan500 as (case when quantity > 500 then quantity end);

查询表时,此列将出现在表中。但是,它不会存储,并且在quantity更改时会自动“更新”。