
在老外网站发布的一些SQL问题,拿过来自己搞一下,后面我也会陆续转载一些问题,欢迎看到的朋友贴出自己的答案,交流一哈。对于技术问答题的描述,翻译远不不原版来的更好一些,下面我就贴出原版的题目,欢迎参与
TSQL Challenge 1 - Pair-wise and ordered assignment of objects from two different lists
This challenge will be interesting for TSQL enthusiasts as well as bird lovers! It involves assigning food items to birds from two different baskets. Here is a ‘relational’ representation of birds, food items and baskets in the form of tables and rows.
Table Birds lists the birds which are the recipients of food items. The baskets containing the food items are the tables Grains and Fruits. Whenever possible, you must assign the food items in pairs and they must be taken from each table in alphabetical order. When one of the tables no longer has a food item for a bird you must output a null in the corresponding column and continue assigning food items from the other table until that one runs out of food baskets as well.
Sample Data
Birds Table
1.
Code Name
2.
---- -------
3.
1 Pigeon
4.
2 Sparrow
5.
3 Parrot
Grains Table
1.
Code Grain
2.
---- ------
3.
1 Wheat
4.
1 Rice
5.
2 Corn
6.
2 Millet
Fruits Table
1.
Code Fruit
2.
---- ------
3.
1 Banana
4.
1 Mango
5.
1 Guava
6.
2 Grapes
Expected Results
1.
Code Bird Grain Fruit
2.
---- ------- ------ ------
3.
1 Pigeon Rice Banana
4.
1 Pigeon Wheat Guava
5.
1 Pigeon NULL Mango
6.
2 Sparrow Corn Grapes
7.
2 Sparrow Millet NULL
8.
3 Parrot NULL NULL
Rules
- For a bird with no food basket at all, a single line should be output with the Grain and Fruit columns containing null.
- The output should be ordered by Code followed by the order in which the Grain/Fruit pairs were extracted from the Grains/Fruits tables.
Restrictions
- The solution should be a single query that starts with a "SELECT" or “;WITH”
下面是我自己的答案,欢迎补充:
;WITH cte AS
(SELECT num=DENSE_RANK()OVER(PARTITION BY name ORDER BY GRain ASC ), * FROM TC1_BIRDS AS D OUTER APPLY (SELECT grain FROM TC1_GRAINS WHERE code=d.code ) AS ST)
,cte2 AS
(SELECT num=DENSE_RANK()OVER(PARTITION BY name ORDER BY fruit ASC ), * FROM TC1_BIRDS AS D OUTER APPLY (SELECT fruit FROM TC1_FRUITS WHERE code=d.code ) AS ST)
,cte3 AS
(
SELECT num,code,NAME,fruit,grain FROM cte2 OUTER APPLY (SELECT grain FROM cte WHERE cte.num=cte2.num AND cte.CODE=CTE2.CODE ) AS ST
UNION ALL
SELECT num,code,NAME,fruit,grain FROM cte OUTER APPLY (SELECT fruit FROM cte2 WHERE cte.num=cte2.num AND CTE2.CODE=cte.CODE ) AS ST
)
SELECT DISTINCT num, code,NAME,grain,fruit FROM cte3 ORDER BY code, NAME
想了半天才凑出上面的答案,欢迎看到的朋友贴出自己的答案。