[英]SQL columns based on select values
希望通過一個查詢來獲取數據,但是列是動態的,基於選定的值。
所以我的表看起來像這樣(使用MySql):
CREATE TABLE 'users' (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL
)
CREATE TABLE `income` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user` int(11) NOT NULL,
`day` int(11) NOT NULL DEFAULT '0',
`action_a` decimal(10,2) NOT NULL DEFAULT '0.00',
`action_b` decimal(10,2) NOT NULL DEFAULT '0.00',
`action_c` decimal(10,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`)
)
CREATE TABLE `given` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`day` int(11) DEFAULT NULL,
`to_user` int(11) NOT NULL,
`from_user` int(11) NOT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`)
)
想進入一個看起來像這樣的查詢表:
+------------+--------------+----------+----------+----------+
| day | action_a | action_b | action_c | user_B | user_C |
+------------+--------------+----------+----------+----------+
| 123 | 123.01 | 123.01 | 123.01 | 123.01 | -123.01 |
| 122 | 324.02 | 234.01 | 123.01 | -123.01 | -123.01 |
| 121 | 987.00 | 345.01 | 123.01 | 123.01 | -123.01 |
| 120 | 9393.01 | 456.01 | 123.01 | -123.01 | -123.01 |
| 119 | 0.00 | 567.01 | 123.01 | -123.01 | -123.01 |
...
用戶列中的負值表示用戶已將其分配給其他用戶
當前,我正在執行3個單獨的查詢,然后合並數據,但是我當前的查詢如下所示:
獲得基於行動的收入
Select action_a, action_b, action_c From income i Join users u on u.id=i.user Where u.name='%s' and i.day=%i Order by i.id desc
得到好評
Select u2.name 'from', amount From given g Join users u on u.id = to_user Join users u2 on u2.id = from_user Where u.name='%s' and amount <> 0.0 Order by g.id
得到給
Select u2.name 'to', amount From given g Join users u on u.id = from_user Join users u2 on u2.id = to_user Where u.name='%s' and amount <> 0.0 Order by g.id desc
歸一化的收入/收入表的示例如下:
CREATE TABLE income
(income_id SERIAL PRIMARY KEY
,dt datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
,user INT NOT NULL
);
CREATE TABLE income_action
(income_id INT NOT NULL
,action CHAR(1) NOT NULL
,value DECIMAL(10,2) NOT NULL DEFAULT '0.00',
,PRIMARY KEY(income_id,action)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.