我创建了四个表,给出了层次类别列表。像分类表;
+----+--------------+---------------+----------------+
| ID | CategoryName | Ref. Category | Something else |
+----+--------------+---------------+----------------+
参考。类别(链接到第1列)
作为一个例子;
+---+------------+---+------+
| 1 | Elektronik | 0 | ... |
| 2 | Drink | 0 | ... |
| 3 | Computer | 1 | ... |
| 4 | Mouse | 3 | ... |
| 5 | Keyboard | 3 | ... |
| 6 | Juice | 2 | ... |
| 7 | Mouse Cable| 4 | ... |
+---+------------+---+------+
员工表:
+------------+------+---------+-----------+
| EmployeeID | Name | Surname | Something |
+------------+------+---------+-----------+
订单表:
+---------+-------+------+-----------+
| OrderID | EmpID | Date | Something |
+---------+-------+------+-----------+
OrderDetails表:
+---------+-----------+----------+-------+------------+
| OrderID | ProductID | Quantity | Price | CategoryID |
+---------+-----------+----------+-------+------------+
我希望得到特定员工特定类别及以上级别的总价格(参考类别最高为0级)总价格如同 for EmployeeID 10
+-----------+------------+--------------+---------------+
| EmployeeID| CategoryId | CategoryName | Total Prices |
| 10 | 7 | Mouse Cable | 3000 |
| 10 | 4 | Mouse | 5000 |
| 10 | 3 | Computer | 12000 |
| 10 | 1 | Elektronik | 35000 |
+-----------+------------+--------------+---------------+
我想创建一个以特定RefID开始的查询,然后使用CategoryID,在下一步中,RefId将是CategoryID并继续像RefID 0那样
答案 0 :(得分:1)
答案很长但查询下方适合你
DECLARE @rowResult TABLE (
EmployeeID int,
CategoryID int,
Total int);
DECLARE @EmployeeID int;
DECLARE @CategoryID int;
DECLARE @RefID int;
SET @EmployeeID = 100;
SET @CategoryID = 7;
SELECT @RefID = RefID FROM CATEGORIES WHERE CategoryID = @CategoryID;
WHILE @RefID > 0
BEGIN
INSERT INTO @rowResult
SELECT e.EmployeeID, d.CategoryID, SUM(d.Quantity * d.Price) AS 'Total'
FROM Employees e
INNER JOIN Orders o ON o.EmpID = e.EmployeeID
INNER JOIN OrderDetails d ON d.OrderID = o.OrderID
WHERE e.EmployeeID = @EmployeeID AND d.CategoryID = @CategoryID
GROUP BY e.EmployeeID, d.CategoryID ;
SET @CategoryID = @RefID;
SELECT @RefID = RefID FROM CATEGORIES WHERE CategoryID = @CategoryID;
END
SELECT * FROM @rowResult
GO
答案 1 :(得分:1)
Runnnig代码如下 http://rextester.com/VSNF73112
分类
CREATE TABLE CATEGORIES (
CategoryID int NOT NULL PRIMARY KEY,
CategoryName nvarchar(255),
RefID int,
Detail nvarchar(255)
);
EMPLOYEES
CREATE TABLE EMPLOYEES (
EmployeeID int NOT NULL PRIMARY KEY,
Name nvarchar(255),
SurName nvarchar(255),
Detail nvarchar(255)
);
订单明细
CREATE TABLE OrderDetails (
OrderID int,
ProductID int,
Quantity int,
Price int,
CategoryID int
);
订单
CREATE TABLE Orders (
OrderID int,
EmpID int
);
ALTER TABLE CATEGORIES
ADD FOREIGN KEY (RefID) REFERENCES CATEGORIES(CategoryID);
GO