sql >> Databáze >  >> RDS >> Sqlserver

Získejte všechny položky prodané na základě kolekce položek z hlavní tabulky na serveru SQL Server

Pravděpodobně se tam dostanete nejvíce. Nedal jsem do logiky přesun souhrnných sloupců, protože to by fungovalo pouze pro dvě kategorie a předpokládám, že jich máte mnohem více.

CREATE TABLE #Master(ItemNo int,[Name] varchar(50), Category varchar(5)) 
INSERT INTO #Master VALUES(10001,'Apple','C1' )   
INSERT INTO #Master VALUES(10002, 'Coffee' ,'C1')  
INSERT INTO #Master VALUES(10003,'Bread','C2')   
INSERT INTO #Master VALUES(10004,'Beans' ,'C2')  

CREATe TABLE #Transactions(SiteID int,BusinessDate date,ItemName varchar(50),[Units Sold]int,[Units Sale]int,ItemNo int,  OrderNo varchar(20))
INSERT INTO #Transactions VALUES(1,'06/08/2018','Apple',1,5,10001,'122-1')
INSERT INTO #Transactions VALUES(1,'06/08/2018','Coffee',1,16,10002,'122-1')
INSERT INTO #Transactions VALUES(1,'06/08/2018','Bread',2,7,10003,'122-1')
INSERT INTO #Transactions VALUES(1,'06/08/2018','Beans',9,18,10004,'122-1')
INSERT INTO #Transactions VALUES(1,'06/08/2018','Apple',2,5,10001,'122-4')
INSERT INTO #Transactions VALUES(1,'06/08/2018','Coffee',2,6,10002,'122-4')
INSERT INTO #Transactions VALUES(1,'06/08/2018','Bread',1,7,10003,'122-4')
INSERT INTO #Transactions VALUES(1,'06/08/2018','Beans',4,8,10004,'122-4')
INSERT INTO #Transactions VALUES(2,'06/08/2018','Apple',2,5,10001,'122-2')
INSERT INTO #Transactions VALUES(2,'06/08/2018','Coffee',1,6,10002,'122-2')
INSERT INTO #Transactions VALUES(3,'06/08/2018','Bread',3,5,10003,'122-3')
INSERT INTO #Transactions VALUES(3,'06/08/2018','Beans',7,17,10004,'122-3')


;WITH CTE AS (
select MS.ItemNo,MS.Name,MS.Category, SUM(TR.[Units Sold]) RootItemSold, tr.OrderNo
from #Master MS
INNER JOIN #Transactions TR on MS.ItemNo = TR.ItemNo
GROUP BY MS.ItemNo,MS.Name,MS.Category, tr.OrderNo
),
MiddleCalc as
(
select ItemNo, [Name],Category,RootItemSold,OrderNo
,(SELECT ISNULL(SUM(1),0)  FROM CTE T2 where TRoot.OrderNo = t2.OrderNo and TRoot.Category <> t2.Category) HasOtherCategory
from CTE TRoot
)
SELECT ItemNo,[Name],[Category], 
CASE WHEN Category = 'C1' THEN
        SUM(RootItemSold)  
    ELSE
        SUM(CASE WHEN HasOtherCategory <> 0 THEN RootItemSold ELSE 0 END)  END C1,
CASE WHEN Category = 'C2' THEN
        SUM(RootItemSold)  
    ELSE
        SUM(CASE WHEN HasOtherCategory <> 0 THEN RootItemSold ELSE 0 END)  END C2
FROM MiddleCalc
GROUP BY ItemNo,[Name],[Category]


  1. Mysql 5.5 Oprávnění LOAD DATA INFILE

  2. Doba provedení ALTER COLUMN

  3. Spustit problém s mutací

  4. Proč bych neměl vytvořit všechny své pouze PL/SQL VARCHAR2 32767 bajtů?