Это простой вид кросс-таблицы.У меня возникают трудности с передачей моих знаний по SQL в Linq, и из-за того, что его сложно протестировать (я не получил linqpad, работающий должным образом для разработки WP7), я действительно не могу легко "играть".
CREATE TABLE Store
(
StoreID INT NOT NULL,
StoreName VARCHAR(10) NOT NULL
)
INSERT INTO Store (StoreID,StoreName) VALUES (1,'Store A')
INSERT INTO Store (StoreID,StoreName) VALUES (2,'Store B')
CREATE TABLE ProductType
(
ProductTypeID INT NOT NULL,
ProductTypeName VARCHAR(20) NOT NULL
)
INSERT INTO ProductType (ProductTypeID,ProductTypeName) VALUES (1,'Clothing')
INSERT INTO ProductType (ProductTypeID,ProductTypeName) VALUES (2,'Food')
CREATE TABLE Product
(
ProductID INT NOT NULL,
ProductTypeID INT NOT NULL,
ProductName VARCHAR(20) NOT NULL
)
INSERT INTO Product (ProductID,ProductTypeID,ProductName) VALUES (1,1,'Hat')
INSERT INTO Product (ProductID,ProductTypeID,ProductName) VALUES (2,1,'Shirt')
INSERT INTO Product (ProductID,ProductTypeID,ProductName) VALUES (3,1,'Pant')
INSERT INTO Product (ProductID,ProductTypeID,ProductName) VALUES (4,2,'Orange')
INSERT INTO Product (ProductID,ProductTypeID,ProductName) VALUES (5,2,'Apple')
CREATE TABLE Purchase
(
PurchaseID INT NOT NULL,
ProductID INT NOT NULL,
StoreID INT NOT NULL,
Quantity INT NULL,
Amount INT NULL
)
INSERT INTO Purchase (PurchaseID,ProductID,StoreID,Quantity,Amount) VALUES (1,1,1,5,10)
INSERT INTO Purchase (PurchaseID,ProductID,StoreID,Quantity,Amount) VALUES (2,2,1,4,12)
INSERT INTO Purchase (PurchaseID,ProductID,StoreID,Quantity,Amount) VALUES (3,3,1,1,10)
INSERT INTO Purchase (PurchaseID,ProductID,StoreID,Quantity,Amount) VALUES (4,4,1,3,16)
INSERT INTO Purchase (PurchaseID,ProductID,StoreID,Quantity,Amount) VALUES (5,5,1,7,12)
INSERT INTO Purchase (PurchaseID,ProductID,StoreID,Quantity,Amount) VALUES (6,1,2,10,22)
INSERT INTO Purchase (PurchaseID,ProductID,StoreID,Quantity,Amount) VALUES (7,2,2,8,26)
SELECT s.StoreName
,SUM(CASE
WHEN t.ProductTypeID=1 THEN Amount
ELSE 0
END ) as ClothingAmount
,SUM(CASE
WHEN t.ProductTypeID=2 THEN Amount
ELSE 0
END )AS FoodQuantity
,SUM(CASE
WHEN t.ProductTypeID=1 THEN Quantity
ELSE 0
END ) as ClothingAmount
,SUM(CASE
WHEN t.ProductTypeID=2 THEN Quantity
ELSE 0
END )AS FoodQuantity
FROM Purchase u
INNER JOIN Product r
ON u.ProductID=r.ProductID
INNER JOIN ProductType t
ON r.ProductTypeID=t.ProductTypeID
INNER JOIN Store s
ON s.StoreID=u.StoreID
GROUP BY s.StoreName