我需要建模一个可以分解的想法,并考虑如下:
> BookDetails
> BookPrices
这里的问题是你可以有很多书价格,这些价格可能会发生变化.这是一个例子
BookDetails: ----------------- ID Name 1 Harry Potter…
这很容易.
更有意思的是,对于这本书,我当天可能会有十种不同的价格,例如:
BookPrices: ------------------------------------ Book_Details_Id Kind Price 1 SpecialOffer 10 1 BulkPurchase 20 1 Normal 30
我需要在列中提供书籍列表和所有价格 – 例如:
BookName SpecialOffer BulkPurchase Normal Harry Potter… 10 20 30
我的问题是:图书价格表是否应该将所有不同的价格类型作为列?对我来说,这是丑陋的,更好的想法是将每个价格作为一排
如果我使用该方法,我不能想到SQL查询来生成结果集.我整个上午都在考虑这件事.
编辑:我没有计算价格的余地 – 他们必须存储下来.
编辑:这基本上是我能想到的1-n appraoch(感谢下面的评论) – 它实际上是我的想法
SELECT book.bookid,bp1.price,bp2.price FROM book JOIN bookprice bp1 JOIN bookprice bp2 ON bp1.bookid = book.bookid AND bp1.pricetype = 1 AND bp2.bookid = book.bookid AND bp2.pricetype = 2 .. .
问题是10个价格,你会加入十次,这很臭!
解决方法
这个答案是特定于t-sql的,可以使用一点改进,但它适用于sql 2005.
取消注释注释行,它将像MAGIC一样更新! (好吧,不是魔术,而是狡猾的hacky)
DROP TABLE Books DROP TABLE Prices DROP TABLE bookpricing CREATE TABLE Books ( id INT,title VARCHAR(20) ) CREATE TABLE Prices ( id INT,[desc] VARCHAR(20),pricingchange VARCHAR(20)) CREATE TABLE bookpricing ( id INT,bookid INT,priceid INT,bookprice MONEY ) INSERT INTO Books VALUES (1,'Hi Mom') --INSERT INTO Books Values (2,'This is another book') INSERT INTO Prices VALUES (1,'Standard','1') INSERT INTO Prices VALUES (2,'Discount','.5') INSERT INTO Prices VALUES(3,'HyperMarkup','1.5') INSERT INTO prices VALUES(4,'Remaindered','.1') INSERT INTO BookPricing VALUES (1,1,20.00) INSERT INTO BookPricing VALUES (2,2,10.00) INSERT INTO BookPricing VALUES (3,3,30.00) --INSERT INTO BookPricing VALUES (4,30.00) --INSERT INTO BookPricing VALUES (5,15.00) --INSERT INTO BookPricing VALUES (6,4,3.00) SELECT * FROM bookpricing
/ **从http://www.tsqltutorials.com/pivot.php **这个位被盗
DECLARE @columns VARCHAR(max) SELECT @columns = COALESCE(@columns + ',[' + cast(id as varchar) + ']','[' + cast(id as varchar)+ ']') FROM prices DECLARE @query VARCHAR(max) SET @query = ' SELECT * FROM (SELECT BookID,PriceID,BookPrice FROM BookPricing) AS BookTable PIVOT (SUM(bookprice) FOR priceid IN (' + @columns + ') ) AS p' EXECUTE(@query)