选择非标准的Group by in子句

时间:2011-05-18 09:09:36

标签: mysql sql

对不起,如果我重新发明轮子(以及我的英语也是如此),也许不可能使用简单的香草查询,但我有“nonsence Idea”可能将行块移动到Resulsets顶部,我希望这个SQL转储(MySql)并且为了更好的不受欢迎我将其转换为帐户及其货币,也许这些会更好地说明我尝试的内容,真的是通过订购而不是我的一杯java

DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (
  `idAccount` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `idCustomer` int(10) unsigned DEFAULT NULL,
  `idCustomerNumber` varchar(6) DEFAULT NULL,
  `AccountNumber` varchar(12) DEFAULT NULL,
  `Currency` varchar(3) DEFAULT NULL,
  PRIMARY KEY (`idAccount`)
) 

INSERT INTO `account` (`idAccount`,`idCustomer`,`idCustomerNumber`,`AccountNumber`,`Currency`) VALUES 
 (1,1,'000001','000001JPY101','JPY'),
 (2,1,'100002','100002GBP101','GBP'),
 (3,2,'003333','003333EUR201','EUR'),
 (4,1,'100002','100002GBP102','GBP'),
 (5,1,'000001','000001EUR101','EUR'),
 (6,1,'000001','000001USD101','USD'),
 (7,1,'000001','000001USD102','USD'),
 (8,1,'100002','100002EUR101','EUR'),
 (9,1,'100002','100002USD101','USD'),
 (10,2,'003333','003333EUR202','EUR'),
 (11,2,'003333','003333JPY201','JPY');

Select * From Account Where CustomerNumber = '000001'

编辑:现在我希望会更好......

如何创建从具有Group by Currenncy和Order by AccountNumber的表中选择,并且可以创建Resultset以例如具有USD货币的AccountNumbers开始,其余行将按字母顺序按货币分组并按AccountNumber排序

提取将按照以下顺序排序的行USD - EUR - JPY

编辑2:

我的坏,抱歉,真的是开始学习主要语言的时间

基本上如果我调用SELECT * FROM Account Where idCustomerNumber = '000001' Order by Currency, AccountNumber,则SQL解释器返回

5,1,"000001","000001EUR101","EUR"
1,1,"000001","000001JPY101","JPY"
6,1,"000001","000001USD101","USD"
7,1,"000001","000001USD102","USD"

但现在我想以编程方式确定Resulset以美元账户开头,其余账户将按货币分组,然后按账户编号按

2 个答案:

答案 0 :(得分:1)

目前尚不清楚你想要什么。也许这个?:

SELECT
    *
FROM
    account
WHERE
    idCustomerNumber = '000001'
ORDER BY
    Currency = 'USD'  DESC
  , Currency
  , AccountNumber ;

答案 1 :(得分:0)

我认为这应该可以帮到你:

 SELECT * FROM account
 WHERE idCustomerNumber = '000001'
 ORDER BY AccountNumber, CASE WHEN Currency = 'USD' THEN 0 WHEN Currency = 'EUR' THEN 1 WHEN Currency = 'JPY' THEN 2 ELSE 0 END

通常当你尝试分组时,你需要考虑你要对你所组合的列做什么,对于分组你需要使用汇总值,例如:假设你有一个Amount列:

 SELECT AccountNumber, Currency, SUM(Amount) AS TotalAmount FROM account
 WHERE idCustomerNumber = '000001'
 GROUP BY AccountNumber, Currency
 ORDER BY AccountNumber, CASE WHEN Currency = 'USD' THEN 0 WHEN Currency = 'EUR' THEN 1 WHEN Currency = 'JPY' THEN 2 ELSE 0 END

至于按美元排序然后欧元然后是日元等等,这最好在CurrencySortOrder表中定义,以便您可以添加更多值而无需更改所有查询等。