需要使用列名帮助取消透视

时间:2017-12-19 08:18:20

标签: sql sqlite unpivot

我有3张桌子

1.User
2.Item
3.Data

表架构:

1.CREATE TABLE User (
'UserID'    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
'UserName'  TEXT NOT NULL,
'TINNUMBER' TEXT)
2.CREATE TABLE ITEM(
 'ItemNo' INTEGER NOT NULL,
 'InvNumber' INTEGER not null
 'ITEMID' TEXT,
 'ItemName'TEXT,
  'Tax1'    INTEGER,
  'Tax2'    INTEGER,
  'Tax3'    INTEGER,
  'Tax4'    INTEGER,)
3.CREATE TABLE DATA(
'InvNumber' INTEGER not null
   'UserID' INTEGER,
   'UserName'   TEXT,
   'TotalAmount'    NUMERIC      
)

select P.TINNUMBER
      ,SI.InvNumber
      ,SI.TotalAmount
      ,SII.ItemName
      ,SII.Tax1
      ,SII.Tax2
      ,SII.Tax3
      ,SII.Tax4 
from SalesInvoices SI 
Inner Join user P ON SI.UserID=P.UserID 
Left Outer Join Item SII on SI.InvNumber=SII.InvNumber

我加入了3个表,但我希望tax1,tax2,tax3和tax4数据显示在行中,其他列数据为sam。需要帮助提前感谢

'<table><tr><th>TINNumber</th><th>InvNumber</th><th>TotalAmount</th><th>ItemName</th><th>Tax1</th></tr>
<tr><th>TINNumber</th><th>InvNumber</th><th>TotalAmount</th>
<th>ItemName</th><th>Tax2</th></tr>
<tr><th>TINNumber</th><th>InvNumber</th><th>TotalAmount</th>
<th>ItemName</th><th>Tax3</th></tr>
<tr><th>TINNumber</th><th>InvNumber</th><th>TotalAmount</th>
<th>ItemName</th><th>Tax4</th></tr></table>'

1 个答案:

答案 0 :(得分:1)

使用UNION ALL取消旋转。不幸的是,Sqlite还没有pivot / unpivot快捷方式。尝试

select P.TINNUMBER
      ,SI.InvNumber
      ,SI.TotalAmount
      ,SII.ItemName
      ,SII.Tax
from SalesInvoices SI 
Inner Join user P ON SI.UserID=P.UserID 
Left Outer Join (
  Select InvNumber, ItemName, Tax1 as Tax
  From Item
  Union All
  Select InvNumber, ItemName, Tax2 as Tax
  From Item
  Union All
  Select InvNumber, ItemName, Tax3 as Tax
  From Item
  Union All
  Select InvNumber, ItemName, Tax4 as Tax
  From Item
 ) SII on SI.InvNumber=SII.InvNumber